Convert Dictionary to List of Tuples in Python

Convert Dictionary to List of Tuples in Python

Dictionary to Tuples

Python dict objects have many useful methods for handling data. One method that is useful for accessing data and converting it to a list of tuples is the dict.items() method.

my_data = {
    "Joe": 1,
    "Jane" : 2,
    "Alice" : 3,
    "Bob" : 4
}

print(list(my_data.items()))
[('Joe', 1), ('Jane', 2), ('Alice', 3), ('Bob', 4)]

The dict.items() method returns a view object, which reflects the current state of the dictionary. Notice the difference in output between the following snippets:

my_data = {
    "Joe": 1,
    "Jane" : 2,
    "Alice" : 3,
    "Bob" : 4
}

my_tuple_view = my_data.items()
print(my_tuple_view)

my_data["Joe"] = 2
print(my_tuple_view)
dict_items([('Joe', 1), ('Jane', 2), ('Alice', 3), ('Bob', 4)])
dict_items([('Joe', 2), ('Jane', 2), ('Alice', 3), ('Bob', 4)])

Note that my_tuple_view reflects the changes in my_data. However, if we cast it as a list:

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

my_data = {
    "Joe": 1,
    "Jane" : 2,
    "Alice" : 3,
    "Bob" : 4
}

my_tuple_list = list(my_data.items())
print(my_tuple_list)

my_data["Joe"] = 2
print(my_tuple_list)
[('Joe', 1), ('Jane', 2), ('Alice', 3), ('Bob', 4)]
[('Joe', 1), ('Jane', 2), ('Alice', 3), ('Bob', 4)]

Now, my_tuple_list values aren't associated to my_data values anymore. Keep this in mind when using the dict.items() method.

One interesting application of the dict.items() method is applying some function to each element of the dictionary, using both the keys and values:

my_data = {
    "Joe": 1,
    "Jane" : 2,
    "Alice" : 3,
    "Bob" : 4
}

my_map = lambda tup : tup[0] + '_' + str(tup[1])
print(list(map(my_map, my_data.items())))
['Joe_1', 'Jane_2', 'Alice_3', 'Bob_4']
Last Updated: November 12th, 2022
Was this helpful?
Project

Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
David Landup
Details
Course

Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup
Details

© 2013-2022 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms