snippetpythonCritical
Create a dictionary with comprehension
Viewed 0 times
comprehensiondictionarycreatewith
Problem
Can I use list comprehension syntax to create a dictionary?
For example, by iterating over pairs of keys and values:
For example, by iterating over pairs of keys and values:
d = {... for k, v in zip(keys, values)}Solution
Use a dict comprehension (Python 2.7 and later):
Alternatively, use the
Given separate lists of keys and values, use the
{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}
Code Snippets
{key: value for key, value in zip(keys, values)}Context
Stack Overflow Q#1747817, score: 2366
Revisions (0)
No revisions yet.