1

Ok so what I have is:

foo = {1: {'f1': 'c1'}, 2: {'f2': 'c2'}}

What I want to get using list comprehension(if possible of course) is merge all 2nd level dictionary values this:

bar = {'f1': 'c1', 'f2': 'c2'}

What I tried is this:

bar = {k:v for k, v in tmp.items() for tmp in list(foo.values())}

Now this gets me:

NameError: name 'tmp' is not defined

This seamed like logical solution but apparently its a no go, could you please suggest a solution using list comprehension if possible, or some other one liner, or if that would not be possible an insight into why I get this error will be good knowledge to have.

Thanks,

jpp
  • 159,742
  • 34
  • 281
  • 339
Dusan Gligoric
  • 582
  • 3
  • 21

1 Answers1

2

You can use a dictionary comprehension:

foo = {1: {'f1': 'c1'}, 2: {'f2': 'c2'}}

bar = {k: v for d in foo.values() for k, v in d.items()}

{'f1': 'c1', 'f2': 'c2'}

You were close, but the order of your nesting is incorrect. This is tricky and not intuitive to everyone. Read your comprehension as you would write a normal for loop.

There is also no need to make a list out of your dictionary values.

Related: Understanding nested list comprehension.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • Many thanks, makes sense, bit mind boggling but works out for me! :) – Dusan Gligoric Apr 27 '18 at 01:19
  • 1
    funny thing is I wrote loop that looks exactly same as when you untie this one moments prior to you answering, but wouldn't know how to tie it up in comprehension for sure if it wasn't for this! :) @jpp – Dusan Gligoric Apr 27 '18 at 01:27