HomeBytes
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:
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
David Landup
Editor