Python Dictionary Methods
In this page:
Retrieving Keys, Values, and Items
keys(), values(), and items() return live, dynamic views rather than static copies, meaning they automatically reflect later changes to the dictionary; items() returning (key, value) tuples is what makes 'for k, v in d.items()' the standard iteration pattern.
Example: Retrieving Keys, Values, and Items
user = {"name": "Alex", "age": 30}
print(list(user.keys()))
print(list(user.values()))
print(list(user.items()))
Safe Lookups with get()
get(key, default) looks up a key without ever raising KeyError -- if the key is missing it returns None (or your specified default) instead, which is safer than square-bracket access whenever a key's presence isn't guaranteed.
Example: Safe Lookups with get()
user = {"name": "Alex"}
print(user.get("age"))
print(user.get("age", 0))
Removing Items with pop()
pop(key) removes that key and returns its value (optionally with a default to avoid KeyError on a missing key), while popitem() removes and returns the most recently inserted (key, value) pair as a tuple -- useful for treating a dict like a stack.
Example: Removing Items with pop()
user = {"name": "Alex", "age": 30}
age = user.pop("age")
print(age, user)
Updating and Merging
update() merges another dictionary or an iterable of key-value pairs into the current one in place; matching keys get overwritten with the new values while unmatched keys from the current dict are left untouched.
Example: Updating and Merging
user = {"name": "Alex", "age": 30}
user.update({"age": 31, "city": "NYC"})
print(user)
Default Values and Clearing
setdefault(key, default) returns the existing value if the key is present, or inserts the key with the given default and returns that -- a compact one-line replacement for the common 'if key not in d: d[key] = default' pattern. clear() empties the dictionary entirely.
Example: Default Values and Clearing
user = {"name": "Alex"}
user.setdefault("age", 18)
print(user)
user.clear()
print(user)
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: