Create a dictionary with list comprehension Create a dictionary with list comprehension python python

Create a dictionary with list comprehension


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/valsdict(pairs)2) "zip'ped" from two separate iterables of keys/valsdict(zip(list_of_keys, list_of_values))


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.


In fact, you don't even need to iterate over the iterable if it already comprehends some kind of mapping, the dict constructor doing it graciously for you:

>>> ts = [(1, 2), (3, 4), (5, 6)]>>> dict(ts){1: 2, 3: 4, 5: 6}>>> gen = ((i, i+1) for i in range(1, 6, 2))>>> gen<generator object <genexpr> at 0xb7201c5c>>>> dict(gen){1: 2, 3: 4, 5: 6}