views:

623

answers:

3

I like the python list comprehension operator (or idiom, or whatever it is).

Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:

dict = {(k,v) for (k,v) in blah blah blah} # doesn't work :(
+28  A: 

More or less, but use the dict constructor:

d = dict((k,v) for (k,v) in blah blah blah)
fortran
+19  A: 

in py3k dict comprehensions work like this:

d = {k:v for k, v in iterable}

in py2k you can use fortran's suggestion.

SilentGhost
A: 

Use python dict comprehensions: Here's the link to know more about it: Dict Comprehensions

Learner
Maybe you missed the part which says: This PEP is withdrawn. Substantially all of its benefits were subsumed by generator expressions coupled with the dict() constructor.
Michael Dillon