Convert Two Lists Into A Dictionary In Python
Chapter:
Python
Last Updated:
24-05-2023 17:16:05 UTC
Program:
/* ............... START ............... */
keys = ['name', 'age', 'city']
values = ['John', 25, 'New York']
result_dict = dict(zip(keys, values))
print(result_dict)
/* ............... END ............... */
Output
{'name': 'John', 'age': 25, 'city': 'New York'}
Notes:
-
In this example, we have two lists: keys and values. We use the zip() function to combine corresponding elements from both lists, creating a sequence of tuples. Then, the dict() constructor is used to convert this sequence of tuples into a dictionary. The resulting dictionary is stored in the result_dict variable, which is printed to the console. Each element from the keys list becomes a key in the dictionary, and each element from the values list becomes the corresponding value.
Tags
Convert Two Lists Into A Dictionary In Python #How to combine two lists into dictionary in Python #Create dictionary from two lists