Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Properties of Dictionary Keys in Python
Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, the same is not true for dictionary keys.
There are two important points to remember about dictionary keys:
No Duplicate Keys Allowed
More than one entry per key is not allowed. When duplicate keys are encountered during assignment, the last assignment wins ?
# Duplicate keys - last value overwrites previous ones
student = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print("student['Name']:", student['Name'])
print("Full dictionary:", student)
student['Name']: Manni
Full dictionary: {'Name': 'Manni', 'Age': 7}
As you can see, the first 'Name': 'Zara' entry was overwritten by 'Name': 'Manni'.
Keys Must Be Immutable
Dictionary keys must be immutable (hashable) objects. You can use strings, numbers, or tuples as keys, but mutable objects like lists are not allowed ?
Valid Immutable Keys
# Valid keys: strings, numbers, tuples
valid_dict = {
'string_key': 'value1',
42: 'value2',
(1, 2): 'value3',
3.14: 'value4'
}
print("Valid dictionary:", valid_dict)
Valid dictionary: {'string_key': 'value1', 42: 'value2', (1, 2): 'value3', 3.14: 'value4'}
Invalid Mutable Keys
Attempting to use a mutable object like a list as a key will raise a TypeError ?
# This will cause an error
invalid_dict = {['Name']: 'Zara', 'Age': 7}
print("This won't work")
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'
Why Keys Must Be Immutable
Python uses a hash table implementation for dictionaries. Hash tables require that keys produce a consistent hash value. If a key could change (like a list), its hash would change, making it impossible to retrieve the stored value.
# Demonstrating hash values
print("Hash of string:", hash('key'))
print("Hash of number:", hash(42))
print("Hash of tuple:", hash((1, 2, 3)))
# Lists don't have hash values
try:
print("Hash of list:", hash([1, 2, 3]))
except TypeError as e:
print("Error:", e)
Hash of string: -6208160604277157117 Hash of number: 42 Hash of tuple: 2528502973977326415 Error: unhashable type: 'list'
Comparison of Key Types
| Key Type | Allowed? | Example | Reason |
|---|---|---|---|
| String | ? Yes | 'name' |
Immutable |
| Integer | ? Yes | 42 |
Immutable |
| Tuple | ? Yes | (1, 2) |
Immutable |
| List | ? No | [1, 2] |
Mutable |
| Dictionary | ? No | {'a': 1} |
Mutable |
Conclusion
Dictionary keys must be unique and immutable. Use strings, numbers, or tuples as keys. Attempting to use mutable objects like lists will raise a TypeError due to their unhashable nature.
