Use the zip() function to create a dictionary from a list of keys and values in Python. This function allows merging two lists together.
Python create a dictionary from a list of keys and values Example
Simple example code. Use one list as the keys for the dictionary and the other as the values.
fruits = ["Apple", "Pear", "Peach", "Banana"]
prices = [80, 50, 60, 30]
fruit_dict = dict(zip(fruits, prices))
print(fruit_dict)
Output:
Another method Using dictionary comprehension syntax
k = ['a', 'b', 'c', 'd']
v = [8, 4, 2, 1]
dict_res = {k: v for k, v in zip(k, v)}
print(dict_res)
Output: {‘a’: 8, ‘b’: 4, ‘c’: 2, ‘d’: 1}
Do comment if you have any doubts and suggestions on this Python List Dictionary topic.
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.