Dictionary Methods
Key dictionary methods: .keys(), .values(), .items(), .update(), .pop(), .setdefault(), .clear().
15 min•By Priygop Team•Updated 2026
Dict Methods
Dict Methods
person = {"name": "Alice", "age": 25, "city": "Mumbai"}
# Iterating
for key in person:
print(f"{key}: {person[key]}")
# .keys(), .values(), .items()
print(list(person.keys())) # ['name', 'age', 'city']
print(list(person.values())) # ['Alice', 25, 'Mumbai']
print(list(person.items())) # [('name','Alice'), ...]
# Best way to iterate
for key, value in person.items():
print(f"{key}: {value}")
# .update() — merge dictionaries
defaults = {"theme": "dark", "lang": "en"}
user_prefs = {"theme": "light"}
defaults.update(user_prefs)
print(defaults) # {'theme': 'light', 'lang': 'en'}
# Python 3.9+ merge operator
merged = defaults | user_prefs
print(merged)
# .setdefault() — set only if missing
config = {"host": "localhost"}
config.setdefault("port", 8080) # adds port
config.setdefault("host", "0.0.0.0") # doesn't change
print(config) # {'host': 'localhost', 'port': 8080}
# Counting pattern
text = "hello world"
counts = {}
for char in text:
counts[char] = counts.get(char, 0) + 1
print(counts)Tip
Tip
Use dict.items() to iterate key-value pairs. Use | (Python 3.9+) to merge dicts. Use .setdefault() to set only if missing.
Diagram
Loading diagram…
Map for dictionaries. Object for records/config. WeakMap for metadata that shouldnt prevent GC.
Common Mistake
Warning
.update() modifies the dict in place and returns None. Don't do result = dict1.update(dict2) — result will be None.
Practice Task
Note
(1) Count character frequency in a string using .get(). (2) Merge two config dicts. (3) Use .setdefault() for a cache pattern.