Wednesday, March 10, 2021

Converting Lists into Dictionary in Python ( sample code )

 

Converting Lists into Dictionary




 

* When we have two lists , it is possible to convert the lists into a dictionary

 

* For example , we have two lists containing the names of the countries and names of their capital cities

 

countries = [ "USA" , "India" , "Russia","China","Germany" ]

 

cities=["Washington","Delhi","Moscow","Beijing","Berlin"]

 

* If the user wants to create a dictionary out of these two lists by taking the elements of 'countries' list as keys and 'cities' list as values , then the dictionary would look like this :

 

d = { "USA":"Washington" , "India":"Delhi" ,

"Russia":"Moscow","China":"Beijing","Germany":"Berlin"}

 

* There are two steps involved to convert the lists into a dictionary

 

Step - 01 :

Create a "ZIP" class object by passing the two lists to the zip() function as :

 

z = zip(countries,cities)

 

The zip() function is useful to convert the sequences into a zip class object . There may be 1 or more sequences that can be passed to the zip() function . Therefore , we passed only 2 lists to the zip() function in the above statement . The resultant zip object is 'z' .

 

Step - 02 :

The second step is to convert the zip object into a dictionary by using the dict() function .

 

d = dict(z)

 

Here , the 0th element of the z object is taken as the 'key' and 1st element is converted into the 'value' . On a similar note , 2nd element is taken as the 'key' and '3rd' element is considered as the 'value' . All the values are stored in the dictionary object 'd' . If the user wants to display 'd' object , then the user can do this by using the following dictionary :

 

d = { "USA":"Washington" , "India":"Delhi" , "Russia":"Moscow" , "China":"Beijing", "Germany":"Berlin" }

 

No comments:

Post a Comment