Python – Using Tuples as Dictionary Keys or Values
In this article, we will learn how to use tuples as dictionary keys or values.
Using tuples as dictionary keys
We can use tuples as dictionary keys if all the elements of tuples are of an immutable data type like strings, numbers, or tuples. If tuples contain mutable data types like lists, they cannot be used as keys of a dictionary.
We can use tuples as dictionary keys by simply using tuples as dictionary keys and giving them corresponding values separated by a colon (:) inside curly braces {}.
E.g.
my_dict = {(1, 2): 25, (3, 4): 50}
We can also use tuples as dictionary keys by first creating an empty dictionary by using an empty pair of braces {} and then adding tuples as keys with corresponding values to the dictionary one by one.
E.g.
my_dict = {}
my_dict[(1, 2)] = 25
my_dict[(3, 4)] = 50
Using tuples as dictionary values
Python dictionary can accept values of any data type: mutable data types like lists and immutable data types like integers, strings, floats, booleans, or tuples. So we can easily use tuples as dictionary values.
We can use tuples as dictionary values by simply giving tuples as values to the corresponding keys separated by a colon (:) enclosed by curly braces {}.
E.g.
my_dict = {"fruits": ("apple", "banana", "mango"), "vegetables": ("potato", "pumpkin", "tomato")}
We can also use tuples as dictionary values by first creating an empty dictionary by using an empty pair of curly braces {} and then adding keys and giving them corresponding tuples as values to the dictionary one by one.
E.g.
my_dict = {}
my_dict["fruits"] = ("apple", "banana", "mango")
my_dict["vegetables"] = ("potato", "pumpkin", "tomato")