Dictionary methods¶
This reference documents all methods available on Python dict objects.
clear()¶
Remove all items from the dictionary.
copy()¶
Return a shallow copy of the dictionary.
fromkeys()¶
Create a new dictionary with keys from an iterable and all values set to the same value.
keys = ["name", "age", "city"]
template = dict.fromkeys(keys, "unknown")
# {"name": "unknown", "age": "unknown", "city": "unknown"}
get()¶
Return the value for a key if it exists, otherwise return the default value. Does not raise KeyError.
person = {"name": "Alice", "age": 30}
print(person.get("name")) # "Alice"
print(person.get("email")) # None
print(person.get("email", "N/A")) # "N/A"
items()¶
Return a view object containing (key, value) tuples. The view reflects changes to the dictionary.
keys()¶
Return a view object containing the dictionary keys. Supports set operations such as &, |, and -.
pop()¶
Remove and return the value for a key. If the key is not found and a default is provided, return the default. If no default is provided, raises KeyError.
person = {"name": "Alice", "age": 30}
age = person.pop("age") # 30
email = person.pop("email", "N/A") # "N/A"
popitem()¶
Remove and return the last inserted (key, value) pair. Raises KeyError if the dictionary is empty.
setdefault()¶
If the key exists, return its value. If it does not exist, insert the key with the default value and return the default.
counts = {"apples": 3}
counts.setdefault("apples", 0) # Returns 3 (key exists)
counts.setdefault("bananas", 0) # Returns 0 (key added)
# counts is now {"apples": 3, "bananas": 0}
update()¶
Update the dictionary with key-value pairs from another dictionary or an iterable of (key, value) pairs. Existing keys are overwritten.
config = {"debug": False, "port": 8080}
config.update({"debug": True, "host": "localhost"})
# {"debug": True, "port": 8080, "host": "localhost"}
values()¶
Return a view object containing the dictionary values.
Operators¶
Merge with | (Python 3.9+)¶
Create a new dictionary by merging two dictionaries. Values from the right-hand dictionary take precedence:
defaults = {"colour": "blue", "size": "medium"}
overrides = {"size": "large"}
config = defaults | overrides
# {"colour": "blue", "size": "large"}
Update with |= (Python 3.9+)¶
Update a dictionary in place:
Unpacking with **¶
Merge dictionaries using unpacking:
Built-in functions¶
len()¶
Return the number of key-value pairs in the dictionary.
dict()¶
Create a dictionary from keyword arguments or an iterable of pairs.