Convert a Dictionary into a List in Python

In this tutorial, we will learn how to convert a dictionary into a list in Python with three different methods.

A Dictionary is an unordered sequence that is mutable.

Certainly, it is used for more flexible operations.

Let’s see how a Dictionary looks like

d = {
       "class" : 8 ,
       "id"  : 123,                # dictionary in form of "key : value" pair
       "name"  : "jagannath"         
    }
    
print (d)                      # unordered sequence
Output :

{'name': 'jagannath', 'id': 123, 'class': 8}

Converting Dictionary into List in Python:

Here we have shown three different methods to convert a dictionary into a list in Python.

  • list() function
  • values() function
  • items() function

Method 1: using list() function

using list( ) function to convert dictionary to list.

d = {
       "class" : 8 ,
       "id"  : 123,                # dictionary in form of "key : value" pair
       "name"  : "jagannath"
    }
    
print (d)

con_list = list(d) # list elements are the keys in dictionary

print (con_list)
Output :

{'name': 'jagannath', 'class': 8, 'id': 123}
['name', 'class', 'id']

 

The above method seems very easy so, let’s check another method.

Method 2: using values() function

Moreover, values in the dictionary can be converted to a list using the same function.

 

d = {
       "class" : 8 ,
       "id"  : 123,                # dictionary in form of "key : value" pair
       "name"  : "jagannath"
    }
    
print (d)

con_list = list(d.values())  # d.values () returns the values in dictionary

print (con_list)
Output :

{'name': 'jagannath', 'id': 123, 'class': 8}
['jagannath', 123, 8]

Method 3: using items() function

Here, Both the key and value of the dictionary can be appended into a list with a pair of tuples as elements.

d = {
       "class" : 8 ,
       "id"  : 123,                # dictionary in form of "key : value" pair
       "name"  : "jagannath"
    }
    

con_list = list(d.items())  # d.items () returns the keys and values in dictionary 

print (con_list)
Output :

[('id', 123), ('class', 8), ('name', 'jagannath')]

Concluding, a dictionary is like a hash table that maps keys with certain values.

Leave a Reply

Your email address will not be published. Required fields are marked *