PYTHON

Using Tuples as Immutable Composite Dictionary Keys

Discover how to use tuples as robust, immutable keys in Python dictionaries. Perfect for storing data associated with multiple identifiers, like coordinates or multi-part IDs.

# Store sensor readings for specific (latitude, longitude) coordinates
sensor_readings = {}

# Using tuples as keys (lat, lon)
sensor_readings[(34.05, -118.25)] = {'temperature': 25, 'humidity': 60}
sensor_readings[(34.05, -118.25)]['pressure'] = 1012 # Update existing entry

sensor_readings[(34.06, -118.26)] = {'temperature': 22, 'humidity': 65, 'pressure': 1010}

print(f"Sensor readings: {sensor_readings}")

# Accessing data using a composite key
coord1 = (34.05, -118.25)
if coord1 in sensor_readings:
    print(f"Reading at {coord1}: {sensor_readings[coord1]}")

# Iterating through dictionary with tuple keys
print("All sensor data:")
for (lat, lon), data in sensor_readings.items():
    print(f"  Lat: {lat}, Lon: {lon} -> Data: {data}")

# Example with another type of composite key: (user_id, item_id)
user_item_ratings = {}
user_item_ratings[(101, 501)] = 4.5
user_item_ratings[(101, 502)] = 3.0
user_item_ratings[(102, 501)] = 5.0

print(f"User item ratings: {user_item_ratings}")
How it works: Python dictionaries require keys to be immutable. While lists are mutable and cannot be used as keys, tuples are immutable and therefore ideal for creating composite keys. This snippet demonstrates using tuples to store and retrieve data associated with multiple related identifiers, such as geographical coordinates or user-item pairs. This pattern is very useful for efficiently organizing and accessing structured data in a dictionary.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs