Python Merge Two Lists into a Dictionary
Suppose we have two lists, one containing keys and the other containing values. We can use Python'szipfunction to merge the two lists into a dictionary.
Example
keys = ['name', 'age', 'city']
values = ['Alice', 25, 'New York']
# Use the zip function to merge two lists into a dictionary
my_dict = dict(zip(keys, values))
print(my_dict)
values = ['Alice', 25, 'New York']
# Use the zip function to merge two lists into a dictionary
my_dict = dict(zip(keys, values))
print(my_dict)
Code Analysis:
keysThe list contains the dictionary's keys.valuesThe list contains the dictionary's values.zip(keys, values)Pair the elements in the two lists to generate an iterable zip object.dict(zip(keys, values))Convert the zip object into a dictionary.print(my_dict)Output the final dictionary.
Output Result:
Example
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Python3 Examples