Skip to content
Advertisement

How can I make a dictionary (dict) from separate lists of keys and values?

I want to combine these:

keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']

Into a single dictionary:

{'name': 'Monty', 'age': 42, 'food': 'spam'}

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement