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'}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With