Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert two lists into a dictionary?

Imagine that you have the following list.

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'} 
like image 743
Guido Avatar asked Oct 16 '08 19:10

Guido


People also ask

Can you turn a list into a dictionary?

To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.

How do I convert a nested list to a dictionary?

Converting a Nested List to a Dictionary Using Dictionary Comprehension. We can convert a nested list to a dictionary by using dictionary comprehension. It will iterate through the list. It will take the item at index 0 as key and index 1 as value.

How do you merge two lists in Python?

In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.


1 Answers

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.

like image 149
Dan Lenski Avatar answered Oct 13 '22 11:10

Dan Lenski