Create a dictionary with list comprehension

flybywire picture flybywire · Nov 17, 2009 · Viewed 893.5k times · Source

I like the Python list comprehension syntax.

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

mydict = {(k,v) for (k,v) in blah blah blah}  # doesn't work

Answer

fortran picture fortran · Nov 17, 2009

Use a dict comprehension:

{key: value for (key, value) in iterable}

Note: this is for Python 3.x (and 2.7 upwards). Formerly in Python 2.6 and earlier, the dict built-in could receive an iterable of key/value pairs, so you can pass it a list comprehension or generator expression. For example:

dict((key, func(key)) for key in keys)

In simple cases you don't need a comprehension at all...

But if you already have iterable(s) of keys and/or values, just call the dict built-in directly:

1) consumed from any iterable yielding pairs of keys/vals
dict(pairs)

2) "zip'ped" from two separate iterables of keys/vals
dict(zip(list_of_keys, list_of_values))