Understanding Mutable Keys in Dictionaries: 5 Practical Examples

Understanding Mutable Keys in Dictionaries: 5 Practical Examples

Yes, keys in a dictionary can be mutable if they are of a mutable data type, such as lists. Here are five examples illustrating this:

  1. Using Lists as Keys:
mutable_key_dict = {}
key = [1, 2, 3]
mutable_key_dict[key] = "Value"
print(mutable_key_dict)  # Output: {[1, 2, 3]: 'Value'}
key[0] = 4
print(mutable_key_dict)  # Output: {[4, 2, 3]: 'Value'}

In this example, the list [1, 2, 3] is used as a key in the dictionary. Modifying the list key also affects the key in the dictionary.

  1. Using Mutable Objects as Keys:
mutable_key_dict = {}
key = {'a': 1}
mutable_key_dict[key] = "Value"
print(mutable_key_dict)  # Output: {{'a': 1}: 'Value'}
key['b'] = 2
print(mutable_key_dict)  # Output: {{'a': 1, 'b': 2}: 'Value'}

Here, a dictionary is used as a key. Modifying the dictionary key also affects the key in the dictionary.

  1. Using Sets as Keys:
mutable_key_dict = {}
key = {1, 2, 3}
mutable_key_dict[key] = "Value"
print(mutable_key_dict)  # Output: {{1, 2, 3}: 'Value'}
key.add(4)
print(mutable_key_dict)  # Output: {{1, 2, 3, 4}: 'Value'}

In this case, a set is used as a key. Adding elements to the set key also affects the key in the dictionary.

  1. Using Custom Mutable Objects as Keys:
class CustomKey:
    def __init__(self, value):
        self.value = value

    def __hash__(self):
        return hash(self.value)

    def __eq__(self, other):
        return isinstance(other, CustomKey) and self.value == other.value

mutable_key_dict = {}
key = CustomKey(5)
mutable_key_dict[key] = "Value"
print(mutable_key_dict)  # Output: {<__main__.CustomKey object at 0x7fcd40826550>: 'Value'}
key.value = 6
print(mutable_key_dict)  # Output: {<__main__.CustomKey object at 0x7fcd40826550>: 'Value'}

In this example, a custom class CustomKey is used as a key. Modifying the value attribute of the key object also affects the key in the dictionary.

  1. Using Mutable Byte Arrays as Keys:
mutable_key_dict = {}
key = bytearray(b'hello')
mutable_key_dict[key] = "Value"
print(mutable_key_dict)  # Output: {bytearray(b'hello'): 'Value'}
key[0] = ord('H')
print(mutable_key_dict)  # Output: {bytearray(b'Hello'): 'Value'}

Here, a bytearray is used as a key. Modifying elements of the bytearray key also affects the key in the dictionary.

In each example, modifications to the mutable objects used as keys directly affect the keys in the dictionary.

Did you find this article valuable?

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