How to construct nested dictionary comprehension in Python with correct ordering?

Viewed 5338

I was trying to shorten the code for this problem when I encountered the problem.

Basically, I was trying a nested dictionary comprehension & was unsuccessful in the attempt. Here is what I tried.

dict2 = {key:value for key, value in line.split(":")
                   for line in ["1:One", "2:Two", "4:Four"]}
print dict2

When I run this, it gives me

NameError: name 'line' is not defined

And, when I reverse the for statements like this

dict2 = {key:value for line in ["1:One", "2:Two", "4:Four"]
                   for key, value in line.split(":")}
print dict2

It results in

ValueError: need more than 1 value to unpack

I need help on the nesting structure of dictionary (or list) comprehension. An example would be help a lot.

2 Answers
Related