
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Dictionary to List of Tuples in Python
Converting from one collection type to another is very common in python. Depending the data processing needs we may have to convert the key value pairs present in a dictionary to pairs representing tuples in a list. In this article we will see the approaches to achieve this.
With in
This is a straight forward approach where we just consider the
Example
Adict = {30:'Mon',11:'Tue',19:'Fri'} # Given dictionary print("The given dictionary: ",Adict) # Using in Alist = [(key, val) for key, val in Adict.items()] # Result print("The list of tuples: ",Alist)
Output
Running the above code gives us the following result −
The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'} The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]
With zip
The zip function combines the items passed onto it as parameters. So we take the keys and values of the dictionary as parameters to the zip function and put the result under a list function. The key value pair become tuples of the list.
Example
Adict = {30:'Mon',11:'Tue',19:'Fri'} # Given dictionary print("The given dictionary: ",Adict) # Using zip Alist = list(zip(Adict.keys(), Adict.values())) # Result print("The list of tuples: ",Alist)
Output
Running the above code gives us the following result −
The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'} The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]
With append
In this approach we take a empty list and append evry pair of key value as tuples. A for loop is designed to convert the key value pair into tuples .
Example
Adict = {30:'Mon',11:'Tue',19:'Fri'} # Given dictionary print("The given dictionary: ",Adict) Alist = [] # Uisng append for x in Adict: k = (x, Adict[x]) Alist.append(k) # Result print("The list of tuples: ",Alist)
Output
Running the above code gives us the following result −
The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'} The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]