Can You Use Tuples as Keys in Python Dictionaries?

Can You Use Tuples as Keys in Python Dictionaries?

Yes, you can use tuples as keys in dictionaries in Python. Tuples are unchangeable and hashable, which makes them good for dictionary keys. Here are five examples showing how to use tuples as keys in dictionaries:

  1. Using a Tuple of Integers as a Key:
# Creating a dictionary with a tuple of integers as keys
my_dict = {(1, 2): 'value1', (3, 4): 'value2'}

# Accessing values using tuple keys
print(my_dict[(1, 2)])  # Output: value1
print(my_dict[(3, 4)])  # Output: value2
  1. Using a Tuple of Strings as a Key:
# Creating a dictionary with a tuple of strings as keys
my_dict = {('a', 'b'): 'value1', ('c', 'd'): 'value2'}

# Accessing values using tuple keys
print(my_dict[('a', 'b')])  # Output: value1
print(my_dict[('c', 'd')])  # Output: value2
  1. Using a Tuple of Mixed Data Types as a Key:
# Creating a dictionary with a tuple of mixed data types as keys
my_dict = {('John', 25, 'male'): 'value1', ('Alice', 30, 'female'): 'value2'}

# Accessing values using tuple keys
print(my_dict[('John', 25, 'male')])  # Output: value1
print(my_dict[('Alice', 30, 'female')])  # Output: value2
  1. Using Nested Tuples as Keys:
# Creating a dictionary with nested tuples as keys
my_dict = {((1, 2), ('a', 'b')): 'value1', ((3, 4), ('c', 'd')): 'value2'}

# Accessing values using tuple keys
print(my_dict[((1, 2), ('a', 'b'))])  # Output: value1
print(my_dict[((3, 4), ('c', 'd'))])  # Output: value2
  1. Using Tuple of Tuples as Keys:
# Creating a dictionary with tuple of tuples as keys
my_dict = {((1, 2), (3, 4)): 'value1', ((5, 6), (7, 8)): 'value2'}

# Accessing values using tuple keys
print(my_dict[((1, 2), (3, 4))])  # Output: value1
print(my_dict[((5, 6), (7, 8))])  # Output: value2

In each example, a dictionary is created using tuples as keys, and values are accessed with these tuple keys. Tuples are flexible and can have elements of any immutable data type, making them useful for representing many types of keys in dictionaries.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!