Python - How To Convert Dictionary to Tuples in Python

ID : 196

viewed : 153

Tags : PythonPython Dictionary

vote vote

99

In Python, we have different collections available to us, and at times we may need to convert one collection to another as per our needs.

A dictionary is used to store key-value pairs in Python. This tutorial will discuss different methods to store these key-value pairs as tuples in a list.

Use the items() Function to Convert a Dictionary to a List of Tuples in Python

The items() function returns a view object with the dictionary’s key-value pairs as tuples in a list. We can use it with the list() function to get the final result as a list. The following code implements this.

d1 = {'x':1,'y':2,'z':3} l1 = list(d1.items()) print(l1) 

Output:

[('x', 1), ('y', 2), ('z', 3)] 

Note that below Python 3.x, the iteritems() function can perform the same function.

Use the for Loop to Convert a Dictionary to a List of Tuples in Python

In this method, we iterate through the dictionary using the for loop. We use the keys to access the elements and create tuples, which get appended to an empty list. The following code implements this.

d1 = {'x':1,'y':2,'z':3} l2 =[]  for i in d1:     tpl = (i, d1[i])     l2.append(tpl)  print(l2) 

Output:

[('x', 1), ('y', 2), ('z', 3)] 

Use the List Comprehension Method to a Convert Dictionary to a List of Tuples

List Comprehension is an elegant way of creating lists in a single line of code. For this method we will use the for loop and the items() function together as shown below:

d1 = {'x':1,'y':2,'z':3} l3 = [(v, k) for v, k in d1.items()] print(l3) 

Output:

[('x', 1), ('y', 2), ('z', 3)] 

Use the zip() Function to Convert a Dictionary to a List of Tuples

The zip() function returns a zip-type object by merging two iterable objects and forming a tuple. We can pass this object to the list() function to get the final result in a new list.

d1 = {'x':1,'y':2,'z':3} l4 = list(zip(d1.keys(), d1.values())) print(l4) 

Output:

[('x', 1), ('y', 2), ('z', 3)] 

In the above code, we used the keys() and values() functions to get the list of keys and values from the dictionary, respectively, and combine them using the zip() function.

  • Related HOW TO?