Using dictionary comprehension, dict fromkeys(), or the zip() methods can make a dict form list in Python. Thees All methods create a new dictionary and do not modify the existing list.
Python makes dictionary from list example
Simple example code.
Dictionary Comprehension
fruit_list = ["Apple", "Pear", "Peach", "Banana"]
fruit_dict = {fruit: "In stock" for fruit in fruit_list}
print(fruit_dict)
Output:
Using dict.fromkeys()
This method accepts a list of keys that turn into a dictionary. Optionally, can specify a value to assign to every key.
Without value
fruits = ["Apple", "Pear", "Peach", "Banana"]
fruit_dict = dict.fromkeys(fruits)
print(fruit_dict)
Output: {‘Apple’: None, ‘Pear’: None, ‘Peach’: None, ‘Banana’: None}
With values
Assign ‘Yes’ to every element value.
fruits = ["Apple", "Pear", "Peach", "Banana"]
fruit_dict = dict.fromkeys(fruits, "Yes")
print(fruit_dict)
Output: {‘Apple’: ‘Yes’, ‘Pear’: ‘Yes’, ‘Peach’: ‘Yes’, ‘Banana’: ‘Yes’}
Using zip() method
The zip() method is useful if you want to merge two lists into a dictionary. It’s actually making a dictionary from two lists.
fruits = ["Apple", "Pear", "Peach", "Banana"]
prices = [80, 50, 60, 30]
fruit_dict = dict(zip(fruits, prices))
print(fruit_dict)
Output: {‘Apple’: 80, ‘Pear’: 50, ‘Peach’: 60, ‘Banana’: 30}
How to make a dictionary from a list in python example
Answer: As Upper examples, you can use any one of the methods to make a dictionary from a list in python. But if you want to create a dictionary with key-value from only a single list then check the below examples.
dict comprehension
def create(lst):
res = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}
return res
# Driver code
lst = ['a', 1, 'b', 2, 'c', 3]
print(create(lst))
Using zip() method
def create(a):
it = iter(a)
res = dict(zip(it, it))
return res
# Driver code
lst = ['a', 1, 'b', 2, 'c', 3]
print(create(lst))
Output: {‘a’: 1, ‘b’: 2, ‘c’: 3}
Do comment if you have any doubts and suggestions on this Python dict list tutorial.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.