Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert dictionary to list of tuples in Python
Converting from one collection type to another is very common in Python. Depending on the data processing needs we may have to convert the key-value pairs present in a dictionary to tuples in a list. In this article we will see the approaches to achieve this.
Using Dictionary items()
This is the most straightforward approach where we use list comprehension with the items() method to extract key-value pairs as tuples ?
Example
day_dict = {30: 'Mon', 11: 'Tue', 19: 'Fri'}
# Given dictionary
print("The given dictionary:", day_dict)
# Using list comprehension with items()
tuple_list = [(key, val) for key, val in day_dict.items()]
# Result
print("The list of tuples:", tuple_list)
The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]
Using zip() Function
The zip() function combines the items passed to it as parameters. We take the keys and values of the dictionary as parameters to the zip function and convert the result to a list ?
Example
day_dict = {30: 'Mon', 11: 'Tue', 19: 'Fri'}
# Given dictionary
print("The given dictionary:", day_dict)
# Using zip with keys() and values()
tuple_list = list(zip(day_dict.keys(), day_dict.values()))
# Result
print("The list of tuples:", tuple_list)
The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]
Using append() Method
In this approach we take an empty list and append every pair of key-value as tuples. A for loop is designed to convert each key-value pair into tuples ?
Example
day_dict = {30: 'Mon', 11: 'Tue', 19: 'Fri'}
# Given dictionary
print("The given dictionary:", day_dict)
tuple_list = []
# Using append in a loop
for key in day_dict:
pair = (key, day_dict[key])
tuple_list.append(pair)
# Result
print("The list of tuples:", tuple_list)
The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
items() |
High | Best | General use |
zip() |
Medium | Good | When keys/values are separate |
append() |
Low | Slowest | When additional logic is needed |
Conclusion
The items() method with list comprehension is the most efficient and readable approach for converting dictionaries to lists of tuples. Use zip() when working with separate key and value collections, and append() when you need additional processing during conversion.
