Skip to content

Dictionary methods

This reference documents all methods available on Python dict objects.

clear()

dict.clear()

Remove all items from the dictionary.

data = {"a": 1, "b": 2}
data.clear()
# data is now {}

copy()

dict.copy()

Return a shallow copy of the dictionary.

original = {"a": 1, "b": 2}
duplicate = original.copy()

fromkeys()

dict.fromkeys(iterable, value=None)

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()

dict.get(key, default=None)

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()

dict.items()

Return a view object containing (key, value) tuples. The view reflects changes to the dictionary.

person = {"name": "Alice", "age": 30}
for key, value in person.items():
    print(f"{key}: {value}")

keys()

dict.keys()

Return a view object containing the dictionary keys. Supports set operations such as &, |, and -.

person = {"name": "Alice", "age": 30}
print(list(person.keys()))  # ["name", "age"]

pop()

dict.pop(key, default)

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()

dict.popitem()

Remove and return the last inserted (key, value) pair. Raises KeyError if the dictionary is empty.

person = {"name": "Alice", "age": 30}
last = person.popitem()  # ("age", 30)

setdefault()

dict.setdefault(key, default=None)

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()

dict.update(mapping_or_iterable)

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()

dict.values()

Return a view object containing the dictionary values.

prices = {"apples": 1.50, "bread": 1.20}
print(list(prices.values()))  # [1.50, 1.20]

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:

config = {"colour": "blue"}
config |= {"size": "large"}

Unpacking with **

Merge dictionaries using unpacking:

merged = {**defaults, **overrides}

Built-in functions

len()

Return the number of key-value pairs in the dictionary.

print(len({"a": 1, "b": 2}))  # 2

dict()

Create a dictionary from keyword arguments or an iterable of pairs.

person = dict(name="Alice", age=30)
prices = dict([("apples", 1.50), ("bread", 1.20)])