0 votes
1 view
in Python by (47.8k points)

Imagine that you have:

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

What is the simplest way to produce the following dictionary?

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

1 Answer

0 votes
by (107k points)

To convert list values into dictionary the pairwise dict constructor and zip function are awesomely useful: 


The dict() constructor creates dictionaries directly from lists of key-value pairs.


The zip() function in Python returns a zip object, which is an iterator of list/tuple where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together, etc.

The following code is an example that solves your problem:-

keys = ['a', 'b', 'c'] 

values = [1, 2, 3]

dictionary = dict(zip(keys, values)) 



Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !