HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

Create a dictionary with comprehension

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
dictionarywithcomprehensioncreate

Problem

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)}

Solution

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}

Code Snippets

{key: value for key, value in zip(keys, values)}

Context

Stack Overflow Q#1747817, score: 2366

Revisions (0)

No revisions yet.