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

Make a dictionary (dict) from separate lists of keys and values

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

Problem

I want to combine these:
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']


into a single dictionary:
{'name': 'Monty', 'age': 42, 'food': 'spam'}


How can I do this?

Solution

Like this:

keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary) # {'a': 1, 'b': 2, 'c': 3}


Voila :-) The pairwise dict constructor and zip function are awesomely useful.

Code Snippets

keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary) # {'a': 1, 'b': 2, 'c': 3}

Context

Stack Overflow Q#209840, score: 2998

Revisions (0)

No revisions yet.