Python 3 reference · 11 entries

Python Dictionary Methods

Every Python dictionary method, from get() to update(), with syntax, parameters and runnable examples for working with keys and values.

Dictionaries map keys to values and keep insertion order. Look up with d[key] or d.get(key).

NameDescriptionSince
dict.clear() Remove every key and value from the dictionary in place, leaving it empty. Other references see the change too. 3.0
dict.copy() Return a shallow copy of the dictionary: a new dict with the same keys and values (nested values are shared). 3.0
dict.fromkeys() Create a new dictionary with the given keys, all set to the same value (None by default). 3.0
dict.get() Return the value for a key, or a default (None unless given) if the key is missing, without raising KeyError. 3.0
dict.items() Return a live view of the dictionary's (key, value) pairs, used to loop over keys and values together. 3.0
dict.keys() Return a live view of the dictionary's keys. Supports len(), in and set operations such as & and |. 3.0
dict.pop() Remove a key and return its value. Returns the default if given and the key is missing; otherwise raises KeyError. 3.0
dict.popitem() Remove and return the last inserted (key, value) pair (LIFO order). Raises KeyError if the dict is empty. 3.0
dict.setdefault() Return the value for a key; if the key is missing, insert it with a default value first and return that. 3.0
dict.update() Add or overwrite keys from another mapping, an iterable of pairs, or keyword arguments, in place. 3.0
dict.values() Return a live view of the dictionary's values, for looping or for functions such as sum() and max(). 3.0