Tuesday, November 8, 2016




How to convert a Dictionary into a list and vice-versa in python?

A: If D is a Dictionary in python 3.x we can pass the D.items() dictionary view to the list constructor to convert the dictionary to a list. Below screenshot if from python 3.5.1


Code for python 2.x (below screenshot is from 2.7.12)


You can also create a list by retrieving only the Dictionary values.


Note:- In python 2.x; D.items() returns a list while in 3.x it returns a dictionary view object.
 In 3.5.1                                In 2.7.12
                        

And, of course, the elements of the list are tuples.
              In 3.5.1                                                                 In 2.7.12

Also note that unlike in python 2.x the built-in data types python 3.x are classes.

Now, you can simply use the dict() function to create a dictionary from a list.


No comments:

Post a Comment