Can I use list comprehension syntax to create a dictionary?
For example, by iterating over pairs of keys and values:
d = {... for k, v in zip(keys, values)}
Use a dict comprehension (Python 2.7 and later):
{key: value for key, value in zip(keys, values)}
Alternatively, use the dict
constructor:
pairs = [('a', 1), ('b', 2)]
dict(pairs) # → {'a': 1, 'b': 2}
dict((k, v + 10) for k, v in pairs) # → {'a': 11, 'b': 12}
Given separate lists of keys and values, use the dict
constructor with zip
:
keys = ['a', 'b']
values = [1, 2]
dict(zip(keys, values)) # → {'a': 1, 'b': 2}