Topic 27 of 58
Dictionary Methods
Overview
To work effectively with dictionaries, you need to know how to iterate through them and merge them. Python provides native 'view objects' (keys(), values(), and items()) that allow you to loop through dictionary contents dynamically. Understanding these methods is critical for transforming JSON responses in backend applications.
Syntax
python
config = {"host": "localhost", "port": 8080}
# 1. Iterate over keys (Default behavior)
for key in config.keys():
print(key)
# 2. Iterate over values
for val in config.values():
print(val)
# 3. Iterate over BOTH (Most common pattern)
for key, val in config.items():
print(f"Key: {key}, Value: {val}")
# Removing items safely
port = config.pop("port") # Removes 'port' and returns 8080
del config["host"] # Deletes 'host' (returns nothing)Common Pitfalls
- Attempting to add or delete keys from a dictionary while iterating over it. This throws a
RuntimeError: dictionary changed size during iteration. If you need to mutate keys, iterate over a static list of the keys:for k in list(config.keys()):.
Interview Questions
Q:
How do you elegantly merge two dictionaries in Python 3.9+?
A:
Using the merge operator |. For example: merged = dict_a | dict_b. If there are duplicate keys, the values from the dictionary on the right (dict_b) will overwrite the ones on the left.
Real-World Example
Applying custom user settings on top of default application settings.
example
python
default_settings = {"theme": "light", "notifications": True, "volume": 50}
user_settings = {"theme": "dark", "volume": 80}
# The .update() method mutates the original dictionary in-place,
# overwriting existing keys and adding new ones.
default_settings.update(user_settings)
print(default_settings)
# {'theme': 'dark', 'notifications': True, 'volume': 80}Check Your Knowledge
Test your understanding of Dictionary Methods with these quick questions.