1. What Is a Dictionary (dict)
A dictionary is an important built-in data structure in Python, used to store mappings between keys and values.
Unlike lists, which access elements by integer index, dictionaries access values by key.
For example:
user = {
"name": "Alice",
"age": 25,
"city": "Tokyo"
}
print(user["name"]) # Alice
print(user["age"]) # 25
In this dictionary:
| Key | Value |
|---|---|
"name" |
"Alice" |
"age" |
25 |
"city" |
"Tokyo" |
You can think of a dictionary as a lookup table:
Key Value
--------------------------------------
"name" ─────────> "Alice"
"age" ─────────> 25
"city" ─────────> "Tokyo"
The core features of a dictionary are:
- Key-value mapping: Each key corresponds to one value.
- Unique keys: Duplicate keys cannot exist in the same dictionary.
- Values can be duplicated: Multiple different keys can point to the same value.
- Mutable structure: Key-value pairs can be added, modified, and deleted.
- Keys must be hashable: Keys need to satisfy hashing and equality requirements.
- Insertion order is preserved: Starting with Python 3.7, dictionary insertion order is guaranteed by the language specification.
- High lookup efficiency: On average, key lookup, insertion, and deletion are close to O(1).
A dictionary is a mapping type (Mapping); its core is not the position of elements but the association between keys and values.
2. Basic Structure of a Dictionary
1. Dictionary Syntax
A dictionary is defined using curly braces {}. Each key-value pair is separated by a comma, and keys and values are separated by a colon.
person = {
"name": "Alice",
"age": 25,
"gender": "female"
}
Basic syntax:
{
key1: value1,
key2: value2,
key3: value3
}
Where:
key: The key, used to locate data.value: The value, used to store the actual content.:: Separates the key and value.,: Separates different key-value pairs.
2. Creating an Empty Dictionary
You can use {} or dict() to create an empty dictionary.
data1 = {}
data2 = dict()
print(data1) # {}
print(data2) # {}
Note:
value = {}
print(type(value)) # <class 'dict'>
An empty {} represents a dictionary, not a set.
To create an empty set, use:
items = set()
print(type(items)) # <class 'set'>
3. Creating a Dictionary Directly
user = {
"id": 1001,
"name": "Alice",
"age": 25
}
4. Creating a Dictionary with dict()
When the keys are valid Python identifiers, you can create a dictionary using keyword arguments:
user = dict(
name="Alice",
age=25,
city="Tokyo"
)
print(user)
You can also create one from a sequence of key-value pairs:
data = dict([
("name", "Alice"),
("age", 25),
("city", "Tokyo")
])
print(data)
Use zip() to combine two sequences into a dictionary:
keys = ["name", "age", "city"]
values = ["Alice", 25, "Tokyo"]
user = dict(zip(keys, values))
print(user)
If the two sequences have different lengths, zip() stops at the shorter one by default.
5. Dictionary Comprehensions
Dictionary comprehensions let you build a dictionary dynamically from existing data.
numbers = [1, 2, 3, 4, 5]
squares = {
number: number ** 2
for number in numbers
}
print(squares)
Output:
{
1: 1,
2: 4,
3: 9,
4: 16,
5: 25
}
You can add a condition:
numbers = [1, 2, 3, 4, 5, 6]
even_squares = {
number: number ** 2
for number in numbers
if number % 2 == 0
}
print(even_squares)
Dictionary comprehensions are well suited to converting an iterable into a key-value mapping.
III. Keys and Values of a Dictionary
Keys and values in a dictionary are subject to different constraints.
1. Keys Must Be Unique
Keys in a dictionary cannot be repeated.
If the same key appears when creating a dictionary, the later value overwrites the earlier one.
data = {
"name": "Alice",
"age": 20,
"name": "Bob"
}
print(data)
Output:
{
"name": "Bob",
"age": 20
}
Here "name" keeps only one mapping, and the final value is "Bob".
Modifying an existing key through assignment also does not create a new key-value pair:
user = {"name": "Alice"}
user["name"] = "Bob"
print(user)
2. Values Can Repeat
Different keys can map to the same value.
scores = {
"Alice": 90,
"Bob": 90,
"Charlie": 85
}
Here Alice and Bob have the same score, but their keys differ, so both mappings are preserved.
3. Keys Must Be Hashable
Dictionary keys must be hashable objects.
Common types that can be used as keys:
| Type | Can Be a Key | Notes |
|---|---|---|
int |
Yes | Integers are hashable |
float |
Yes | Generally hashable; watch out for conflicts with keys of equal numeric value |
bool |
Yes | Equal to certain integer keys |
str |
Yes | Strings are immutable |
bytes |
Yes | Byte strings are immutable |
tuple |
Yes, conditionally | All elements must be hashable |
frozenset |
Yes | Immutable set |
list |
No | Mutable and unhashable |
dict |
No | Mutable and unhashable |
set |
No | Mutable and unhashable |
For example:
data = {
"name": "Alice",
100: "number",
(1, 2): "coordinate"
}
print(data["name"])
print(data[100])
print(data[(1, 2)])
The following code raises an error:
data = {
[1, 2]: "value"
}
Error:
TypeError: unhashable type: 'list'
The reason is that lists are mutable, and their hash value cannot satisfy the stability required for dictionary keys.
4. Tuples as Dictionary Keys
Whether a tuple can be used as a dictionary key depends on whether all its elements are hashable.
data = {
(1, 2): "point A",
("Tokyo", "Japan"): "location"
}
However, the following tuple cannot be used as a dictionary key:
key = (1, [2, 3])
data = {
key: "value"
}
Because it contains a list, the entire tuple is also unhashable.
5. The Special Case of True, 1, and 1.0 as Keys
In Python:
print(True == 1) # True
print(1 == 1.0) # True
These values have the same hash value, so they are treated as equal keys in a dictionary.
data = {
True: "boolean",
1: "integer",
1.0: "float"
}
print(data)
print(len(data))
Only one key-value mapping will be retained in the result; subsequent assignments will update the corresponding value.
This means that key uniqueness in a dictionary depends on equality and hashing rules, not just on the apparent type or literal form.
In engineering practice, if the business logic needs to distinguish booleans, integers, and floats, you should design an explicit key structure and avoid mixing them directly.
IV. Dictionary Access and Lookup
1. Accessing Values with Square Brackets
Access a value in a dictionary by its key:
user = {
"name": "Alice",
"age": 25
}
print(user["name"])
print(user["age"])
If you access a nonexistent key, a KeyError will be raised.
print(user["email"])
Error:
KeyError: 'email'
Therefore, when you are not sure whether a key exists, you should not blindly use square-bracket access.
2. Using get() to Safely Retrieve Values
get() is a commonly used lookup method for dictionaries.
user = {
"name": "Alice",
"age": 25
}
print(user.get("name"))
print(user.get("email"))
A nonexistent key returns None by default and does not raise an exception.
You can provide a default value:
email = user.get("email", "未填写")
print(email)
Syntax:
dict.get(key, default=None)
Note:
get() returns the default value only when the key does not exist. If the key exists but its corresponding value is None, it still returns None.
data = {
"name": None
}
print(data.get("name", "Unknown")) # None
print(data.get("age", "Unknown")) # Unknown
Therefore, get() cannot automatically distinguish between:
- The key does not exist.
- The key exists, but its value is
None.
If you need to distinguish between these two cases, use in together with a sentinel object.
3. Using in to Check Whether a Key Exists
user = {
"name": "Alice",
"age": 25
}
print("name" in user) # True
print("email" in user) # False
in checks keys, not values.
print("Alice" in user) # False
print("Alice" in user.values()) # True
4. Using setdefault() to Retrieve or Initialize Values
setdefault() is used to get the value of a specified key. If the key does not exist, it first inserts the default value and then returns that value.
user = {
"name": "Alice"
}
age = user.setdefault("age", 18)
print(age)
print(user)
After execution:
{
"name": "Alice",
"age": 18
}
If the key already exists, the original value is not overwritten.
user = {"age": 25}
age = user.setdefault("age", 18)
print(age) # 25
Syntax:
dict.setdefault(key, default=None)
Note that the default value expression passed in is evaluated before setdefault() is called; even if the key already exists, the default value construction may still be executed.
5. Distinguishing get() from setdefault()
| Method | Key exists | Key does not exist | Modifies the dictionary? |
|---|---|---|---|
get() |
Returns the original value | Returns the default value | No |
setdefault() |
Returns the original value | Inserts the default value and returns it | Possibly |
Example:
data = {"name": "Alice"}
data.get("age", 18)
print(data)
The dictionary does not change.
data.setdefault("age", 18)
print(data)
A new "age" is added to the dictionary.
V. Adding and Modifying Dictionary Entries
Dictionaries are mutable objects, so key-value pairs can be added and modified dynamically.
1. Adding Key-Value Pairs
With bracket assignment, if the key does not exist, a new mapping is added.
user = {
"name": "Alice"
}
user["age"] = 25
user["city"] = "Tokyo"
print(user)
2. Modifying Existing Values
If the key already exists, assignment overwrites the original value.
user = {
"name": "Alice",
"age": 20
}
user["age"] = 25
print(user)
Adding and modifying use the same syntax; the difference depends on whether the key already exists.
3. Bulk Updating with update()
update() can merge the contents of another mapping or a sequence of key-value pairs into the current dictionary.
user = {
"name": "Alice",
"age": 20
}
user.update({
"age": 25,
"city": "Tokyo"
})
print(user)
After execution:
- The existing
"age"is modified. - The nonexistent
"city"is added. - The original
"name"is retained.
You can also use keyword arguments:
user.update(
age=26,
city="Osaka"
)
You can also pass a sequence of key-value pairs:
user.update([
("age", 27),
("country", "Japan")
])
update() modifies the dictionary in place and returns None.
result = user.update({"age": 28})
print(result) # None
4. Merging with Dictionary Unpacking
Starting with Python 3.5, you can use ** to unpack dictionaries and create a new dictionary:
default_config = {
"host": "localhost",
"port": 8000
}
custom_config = {
"port": 9000,
"debug": True
}
config = {
**default_config,
**custom_config
}
print(config)
When multiple dictionaries have the same key, the later value overrides the earlier value.
Starting with Python 3.9, you can also use the merge operator |:
config = default_config | custom_config
This operation creates a new dictionary and does not modify the original dictionaries.
You can use |= to update in place:
default_config |= custom_config
5. Comparison of dictionary merging methods
| Method | Creates a new dictionary? | Modifies the original dictionary? | Python version |
|---|---|---|---|
update() |
No | Yes | All mainstream versions |
{**a, **b} |
Yes | No | Python 3.5+ |
a \| b |
Yes | No | Python 3.9+ |
a \|= b |
No | Yes | Python 3.9+ |
Note that all of the above methods perform a shallow merge. If a value is itself a list or dictionary, the internal objects are not automatically copied after merging.
VI. Dictionary Deletion Operations
1. Using del to delete a specified key
user = {
"name": "Alice",
"age": 25,
"city": "Tokyo"
}
del user["age"]
print(user)
If you delete a key that does not exist, a KeyError is raised.
2. Using pop() to delete and return a value
pop() can delete a specified key and return the deleted value.
user = {
"name": "Alice",
"age": 25
}
age = user.pop("age")
print(age)
print(user)
If the key does not exist, you can provide a default value:
email = user.pop("email", "未填写")
print(email)
If the key does not exist and no default value is provided, a KeyError is raised.
3. Using popitem() to delete the most recently inserted key-value pair
user = {
"name": "Alice",
"age": 25,
"city": "Tokyo"
}
item = user.popitem()
print(item)
print(user)
Starting with Python 3.7, popitem() deletes the most recently inserted key-value pair in last-in, first-out order.
Before Python 3.7, dictionary order was not guaranteed by the language specification, so you should not rely on this behavior.
4. Using clear() to empty a dictionary
user = {
"name": "Alice",
"age": 25
}
user.clear()
print(user) # {}
clear() deletes all key-value pairs in the dictionary, but the dictionary object itself still exists.
5. Comparison of deletion methods
| Method | Purpose | Return value | When the key does not exist |
|---|---|---|---|
del d[key] |
Delete specified key | None | KeyError |
pop(key) |
Delete and return value | The deleted value | KeyError |
pop(key, default) |
Delete and return value | The deleted value or default value | Returns default value |
popitem() |
Delete most recently inserted item | (key, value) |
KeyError when dictionary is empty |
clear() |
Empty dictionary | None |
Not applicable |
VII. Iterating over a dictionary
Dictionaries support multiple iteration methods, allowing you to obtain keys, values, and key-value pairs separately.
1. Iterating over a dictionary directly
user = {
"name": "Alice",
"age": 25,
"city": "Tokyo"
}
for key in user:
print(key)
When iterating over a dictionary directly, the default is to iterate over its keys.
2. Using keys() to Iterate Over Keys
for key in user.keys():
print(key)
keys() returns a dynamic view object (Dictionary View).
It is not a list, but a view linked to the original dictionary.
user = {"name": "Alice"}
keys = user.keys()
user["age"] = 25
print(keys)
As you can see, the view reflects subsequent modifications to the dictionary.
3. Using values() to Iterate Over Values
for value in user.values():
print(value)
values() returns a dynamic view of all values.
4. Using items() to Iterate Over Key-Value Pairs
for key, value in user.items():
print(key, value)
items() returns a key-value pair view, where each element is represented as a 2-tuple.
This is one of the most common ways to iterate over a dictionary.
5. Comparison of Iteration Methods
| Method | Returns | Use Case |
|---|---|---|
for key in d |
Keys | When you only need keys |
d.keys() |
Key view | Check or iterate over keys |
d.values() |
Value view | When you only need values |
d.items() |
Key-value pair view | When you need both keys and values |
6. Modifying a Dictionary During Iteration
It is not recommended to add or delete key-value pairs directly while iterating over a dictionary.
For example:
data = {
"a": 1,
"b": 2,
"c": 3
}
for key in data:
if key == "b":
del data[key]
This type of operation may raise:
RuntimeError: dictionary changed size during iteration
If you need to delete keys that meet certain conditions, you can first collect the keys and then delete them all at once:
data = {
"a": 1,
"b": 2,
"c": 3
}
keys_to_delete = [
key
for key, value in data.items()
if value < 3
]
for key in keys_to_delete:
del data[key]
print(data)
You can also build a new dictionary:
data = {
"a": 1,
"b": 2,
"c": 3
}
filtered = {
key: value
for key, value in data.items()
if value >= 3
}
If you are only modifying the values associated with existing keys without changing the dictionary's size, this can usually be done during iteration, but you should still avoid making the code depend on complex iteration side effects.
8. Common Dictionary Methods
Dictionaries provide a rich set of built-in methods.
| Method | Purpose | Return value |
|---|---|---|
clear() |
Clear the dictionary | None |
copy() |
Shallow copy the dictionary | New dictionary |
fromkeys() |
Create a dictionary from a key sequence | New dictionary |
get() |
Safely get a value | Corresponding value or default value |
items() |
Get a key-value pair view | View object |
keys() |
Get a key view | View object |
values() |
Get a value view | View object |
pop() |
Delete the specified key and return its value | The deleted value |
popitem() |
Delete the last inserted key-value pair | Two-element tuple |
setdefault() |
Get or initialize a key | Corresponding value |
update() |
Batch update | None |
1. copy() Shallow Copy
user = {
"name": "Alice",
"age": 25
}
new_user = user.copy()
new_user["age"] = 30
print(user)
print(new_user)
Modifying top-level key-value pairs in the new dictionary does not affect the original dictionary.
However, copy() is a shallow copy. If the dictionary contains nested objects, the inner objects still share references.
user = {
"name": "Alice",
"scores": [90, 95]
}
new_user = user.copy()
new_user["scores"].append(100)
print(user["scores"])
print(new_user["scores"])
The scores in both dictionaries point to the same list, so modifications affect each other.
2. fromkeys() Create a Dictionary
fromkeys() creates a new dictionary from a set of keys and sets the same initial value for all keys.
keys = ["name", "age", "city"]
user = dict.fromkeys(keys, None)
print(user)
Output:
{
"name": None,
"age": None,
"city": None
}
Special attention is needed: if the initial value is a mutable object, all keys will share the same object.
keys = ["A", "B", "C"]
data = dict.fromkeys(keys, [])
data["A"].append(100)
print(data)
In the result, the lists corresponding to all three keys will change.
Because they reference the same list.
The correct approach is to use a dictionary comprehension:
data = {
key: []
for key in keys
}
data["A"].append(100)
print(data)
This way, each key gets an independent list object.
9. The Underlying Mechanism of Dictionaries: Hash Tables
The efficient lookup capability of dictionaries mainly comes from hash tables.
A hash table is a data structure that maps keys to storage locations through a hash function.
To understand dictionaries, you need to grasp three core concepts:
- Hash function.
- Hash value.
- Hash collision.
1. What Is a Hash Function?
A hash function is responsible for converting a key into an integer hash value.
Python provides the built-in function hash():
print(hash("name"))
print(hash(100))
print(hash((1, 2)))
The hash value helps the dictionary determine where a key may be stored.
For objects that meet the hashing requirements, the hash value must remain stable throughout their lifetime.
The hash value of a string may differ between processes. This is the result of mechanisms such as hash randomization that Python uses to guard against certain hash collision attacks.
Therefore, you should not treat the result of hash() as a stable data identifier across processes or machines, nor should you use it directly as a persistent ID.
2. How a Dictionary Stores Data
The typical lookup process of a dictionary can be abstracted as:
Input Key
|
v
Compute the hash value of Key
|
v
Determine candidate position from the hash value
|
v
Check the key in the candidate position
|
v
Compare hash values and check key equality
|
v
Return Value once a matching key is found
Real implementations also have to handle collisions, empty slots, probe sequences, and table resizing.
3. What Is a Hash Collision
Different keys may produce the same hash value, or may land on the same candidate position after the hash table position calculation.
This situation is called a hash collision.
For example, suppose we have two keys:
key_a = "apple"
key_b = "banana"
Even if their hash values differ, they may still map to the same candidate position after the hash table index calculation.
A hash table must have some way to handle this situation.
Python's dictionary implementation follows the open addressing approach, probing other candidate positions to find a usable slot.
The specific probing strategy is a CPython implementation detail and should not be understood as the only scheme that every Python implementation must adopt.
4. Why Keys Must Satisfy Both Hashing and Equality Requirements
A hash table first uses the hash value to narrow the search range, and then uses the equality check to confirm whether the keys are the same.
Therefore, Python imposes an important requirement on hashable objects:
If two objects are equal, their hash values must be equal.
That is:
a == b
must guarantee:
hash(a) == hash(b)
The converse does not hold:
Having the same hash value does not mean two objects are necessarily equal.
This is also why hash collisions can occur.
5. Custom Objects as Dictionary Keys
By implementing __hash__() and __eq__(), you can make custom objects usable as dictionary keys.
class UserKey:
def __init__(self, user_id):
self.user_id = user_id
def __hash__(self):
return hash(self.user_id)
def __eq__(self, other):
if not isinstance(other, UserKey):
return NotImplemented
return self.user_id == other.user_id
user1 = UserKey(1001)
user2 = UserKey(1001)
data = {
user1: "Alice"
}
print(data[user2])
Although user1 and user2 are two different objects, they have the same user ID, so they are treated as equal keys in the dictionary.
One thing to note:
If the attributes involved in hashing and equality comparison change, the dictionary's lookup behavior may break.
For example:
class UserKey:
def __init__(self, user_id):
self.user_id = user_id
def __hash__(self):
return hash(self.user_id)
def __eq__(self, other):
if not isinstance(other, UserKey):
return NotImplemented
return self.user_id == other.user_id
If the user_id of a UserKey object already placed in a dictionary is modified, its hash value may also change.
The original storage position in the dictionary will not be rearranged automatically, so the corresponding value may no longer be found normally through that object.
In engineering practice, you should use immutable attributes in the hash computation, or simply use an immutable business identifier as the key.
X. Internal Implementation of Python Dictionaries
The Python language specification defines the behavior of dictionaries, but it does not require every Python implementation to use the same underlying structure.
Taking CPython as an example, modern dictionaries use an optimized hash table implementation.
1. Compact Dictionary
Modern CPython dictionaries use a compact internal storage design to reduce memory overhead and support insertion order.
Conceptually, it can be understood as two parts:
- Index structure: helps locate candidate entries based on hash values.
- Entry structure: stores information such as the hash value, key, and value.
This is an abstract model for understanding; the concrete internal structure changes across CPython versions.
2. Why Insertion Order Is Preserved
In Python 3.6, CPython began using the compact dictionary implementation, and that implementation preserved insertion order.
Starting with Python 3.7, dictionary insertion order became a language specification guarantee.
For example:
data = {}
data["name"] = "Alice"
data["age"] = 25
data["city"] = "Tokyo"
print(data)
Iteration outputs the keys in their insertion order.
Modifying the value of an existing key does not change its original position:
data["name"] = "Bob"
If a key is deleted and then reinserted, that key will appear at its new insertion position:
del data["age"]
data["age"] = 30
print(data)
3. Dictionary Resizing
As elements continue to be added, the available space in the hash table gradually decreases.
When the internal space meets certain conditions, the dictionary needs to adjust the table's capacity and index structure.
This process is called resizing.
Resizing usually involves:
- Allocating or adjusting internal storage space.
- Reorganizing the hash table index.
- Ensuring existing key-value entries can continue to be looked up correctly.
The resizing process may incur a noticeable one-time operation cost, but it helps maintain the average efficiency of subsequent operations.
The specific resizing thresholds and implementation strategies are CPython internal details, and business design should not rely on fixed ratios.
4. Why Dictionary Lookups Are Usually Fast
A dictionary uses hash values to quickly locate candidate positions and does not need to compare one by one from beginning to end like an ordinary list.
For example:
users = {
1001: "Alice",
1002: "Bob",
1003: "Charlie"
}
print(users[1002])
Usually, it can locate the corresponding value without iterating over all keys.
However, if many hash collisions occur, lookup efficiency may decrease.
Therefore, the O(1) of a dictionary is an average time complexity, not a worst-case time complexity that can be guaranteed under all circumstances.
XI. Time Complexity of Dictionaries
The average time complexities of common dictionary operations are usually as follows:
| Operation | Average Time Complexity | Description |
|---|---|---|
d[key] |
O(1) | Look up by key |
d.get(key) |
O(1) | Safely look up by key |
key in d |
O(1) | Check whether a key exists |
d[key] = value |
O(1) | Add or modify |
del d[key] |
O(1) | Delete a specified key |
d.pop(key) |
O(1) | Delete and return |
d.update(other) |
O(n) | n is the size of the mapping to process |
d.copy() |
O(n) | Copy all top-level key-value entries |
d.clear() |
O(n) | Clear existing elements |
| Iterating over a dictionary | O(n) | Access all key-value pairs |
These complexities represent average behavior under common implementations.
In special cases such as many hash collisions, the worst-case time complexity of a single lookup, insertion, or deletion may degrade to O(n).
Therefore, the average O(1) of a dictionary should not be understood as a strict worst-case constant-time guarantee.
XII. Differences Between Dictionaries and Other Data Structures
Dictionaries, lists, tuples, and sets are all commonly used data structures in Python, but they have different design goals.