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