Create a dictionary with list comprehension


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
7/5/2019 8:08:46 PM

Accepted Answer

From Python 2.7 and 3 onwards, you should just use the dict comprehension syntax:

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

In Python 2.6 and earlier, the dict built-in can 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)

However if you already have iterable(s) of keys and/or vals, you needn't use a comprehension at all - it's simplest just call the dict built-in directly:

# consumed from any iterable yielding pairs of keys/vals

# "zipped" from two separate iterables of keys/vals
dict(zip(list_of_keys, list_of_values))
5/14/2019 6:58:15 PM

In Python 3 and Python 2.7+, dictionary comprehensions look like the below:

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

For Python 2.6 or earlier, see fortran's answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow