Python dictionary methods
Look up, loop over and update key-value pairs: get, items, keys, update, pop and more.
A dictionary stores values under keys, like a word and its meaning. Its methods read values safely (get), loop over the contents (keys, values, items), and add or remove entries (update, pop, setdefault).
Most used
dict.get()Returns the value for a key, or a default value (None unless you give one) when the key is missing, instead of raising KeyError.dict.items()Returns a live view of a dictionary's key-value pairs as tuples, so you can loop over the key and its value together.dict.keys()Returns a live view of a dictionary's keys, in the order they were added. Loop over it, test it with in, or turn it into a list.dict.pop()Removes a key from a dictionary and returns its value. Give a default to avoid a KeyError when the key is missing.dict.update()Adds the keys and values from another dictionary (or from pairs or keyword arguments), replacing values for keys already there.
All 11 dictionary methods
- dict.clear()Deletes every key and value from a dictionary in place. Every variable that refers to the same dictionary sees it empty.
- dict.copy()Returns a new dictionary with the same keys and values. Adding keys to the copy leaves the original alone, but nested values stay shared.
- dict.fromkeys()Builds a new dictionary whose keys come from a list or other iterable, all set to the same value (None by default).
- dict.get()Returns the value for a key, or a default value (None unless you give one) when the key is missing, instead of raising KeyError.
- dict.items()Returns a live view of a dictionary's key-value pairs as tuples, so you can loop over the key and its value together.
- dict.keys()Returns a live view of a dictionary's keys, in the order they were added. Loop over it, test it with in, or turn it into a list.
- dict.pop()Removes a key from a dictionary and returns its value. Give a default to avoid a KeyError when the key is missing.
- dict.popitem()Removes the entry that was added last to a dictionary and returns it as a (key, value) pair. Raises KeyError when empty.
- dict.setdefault()Returns the value of a key. If the key is missing, it first adds it with the default value, then returns that default.
- dict.update()Adds the keys and values from another dictionary (or from pairs or keyword arguments), replacing values for keys already there.
- dict.values()Returns a live view of all the values in a dictionary, in key order. Handy for totals, maximums and searching values.