Python Lists to Dictionary
When we have two lists, it is possible to convert them into a dictionary. For example, we have two lists containing names of countries and names of their capital cities.
countries = ["USA", "India", "Germany", "France"]
cities = ['Washington', 'New Delhi', 'Berlin', 'Paris']
We want to create a dictionary out of these two lists by taking the elements of 'countries' list as keys and of 'cities' list as values.
There are two steps involved to convert the lists into a dictionary. The first step is to create a 'zip' class object by passing the two lists to zip() function as:
z = zip(countries, cities)
The zip() function is useful to convert the sequences into a zip class object.
The second step is to convert the zip object into a dictionary by using dict() function.
d = dict(z)
Lists to Dictionary
A Python program to convert the elements of two lists into key-value pairs of a dictionary.
countries = ["USA", "India", "Germany", "France"]
cities = ['Washington', 'New Delhi', 'Berlin', 'Paris']
z = zip(countries, cities)
d = dict(z)
print('{:15s} -- {:15s}'.format('COUNTRY', 'CAPITAL'))
for k in d:
print('{:15s} -- {:15s}'.format(k, d[k]))