Python dictionary with keys having multiple inputs

When working with Python dictionaries, you can use tuples as keys to create dictionary entries where each key consists of multiple values. This is useful when you need to map combinations of values to specific results.

Below is the demonstration of the same −

Example

my_dict = {}

a, b, c = 15, 26, 38
my_dict[a, b, c] = a + b - c

a, b, c = 5, 4, 11
my_dict[a, b, c] = a + b - c

print("The dictionary is :")
print(my_dict)

The output of the above code is −

The dictionary is :
{(15, 26, 38): 3, (5, 4, 11): -2}

How It Works

When you use my_dict[a, b, c], Python automatically creates a tuple (a, b, c) as the key. Tuples are immutable and hashable, making them valid dictionary keys.

Accessing Values with Multiple Keys

my_dict = {(15, 26, 38): 3, (5, 4, 11): -2}

# Access using tuple key
result = my_dict[(15, 26, 38)]
print("Value for key (15, 26, 38):", result)

# Check if key exists
if (5, 4, 11) in my_dict:
    print("Key (5, 4, 11) exists with value:", my_dict[(5, 4, 11)])
Value for key (15, 26, 38): 3
Key (5, 4, 11) exists with value: -2

Practical Use Case

# Store coordinates and their distances from origin
coordinates = {}

# Adding coordinate points as keys
coordinates[0, 0] = 0
coordinates[3, 4] = 5  # distance = sqrt(3^2 + 4^2) = 5
coordinates[1, 1] = 1.41

print("Coordinates dictionary:")
for point, distance in coordinates.items():
    print(f"Point {point}: Distance = {distance}")
Coordinates dictionary:
Point (0, 0): Distance = 0
Point (3, 4): Distance = 5
Point (1, 1): Distance = 1.41

Key Points

  • Python automatically converts my_dict[a, b, c] to my_dict[(a, b, c)]

  • Tuples are immutable and hashable, making them valid dictionary keys

  • This technique is useful for mapping coordinate pairs, combinations, or multi-dimensional data

  • You can use any number of values as a composite key

Conclusion

Using tuples as dictionary keys allows you to create mappings with multiple input values. This technique is particularly useful for coordinate systems, multi-dimensional lookups, and storing relationships between multiple variables.

Updated on: 2026-03-25T19:15:40+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements