Python Dictionary Methods
In this page:
dict_name.get(key, default)
dict_name.keys()
dict_name.values()
dict_name.items()
dict_name.update(other_dict)
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())) # just the keys
print(list(user.values())) # just the values
print(list(user.items())) # (key, value) tuples
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")) # missing key returns None instead of raising an error
print(user.get("age", 0)) # custom default when the key is missing
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") # removes "age" and returns its value
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"}) # age is overwritten, city is added
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) # inserts "age": 18 since the key is missing
print(user)
user.clear() # removes every key
print(user)
- Modifying a dictionary while looping over
d.items()ord.keys(), which raisesRuntimeError: dictionary changed size during iteration; loop overlist(d)instead. - Using
pop(key)on a missing key without a default, which raisesKeyError; used.pop(key, None). - Expecting
d.update(other)to return the merged dictionary, when it changesdin place and returnsNone.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: