Coding

Dictionary in Python: Examples, Methods, Looping and Merging

A dictionary in Python is a collection of unique keys, each mapped to a value, written with braces: {"name": "Ada", "age": 36}. You read a value with d["name"], add or change one with d["city"] = "London", and remove one with del d["age"].

The examples below follow the official Python documentation. Lines that start with >>> are an interactive session, and the lines under them are example output.

How to create a dictionary in Python

A dictionary is a set of key: value pairs, and the keys must be unique within one dictionary. A pair of braces creates an empty one. The three common ways to build a populated one:

>>> tel = {'jack': 4098, 'sape': 4139}
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}

The braces form is the one you will use most. The dict() constructor builds a dictionary from a sequence of key-value pairs, which is handy when the pairs come from another calculation. The keyword form is shorter, but it only works when the keys are simple strings that are valid as argument names.

What can be a key

Dictionaries are indexed by keys, and a key can be any immutable type. Strings and numbers always work. A tuple works only if it contains strings, numbers or other tuples; if it holds a mutable object, directly or indirectly, it cannot be a key. Lists are out, because they can be changed in place with index assignment, slice assignment, or methods such as append() and extend(). Values have no such restriction: a value can be a list, another dictionary, or anything else.

How to read, add, update and delete items

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}

Assigning to a key that does not exist adds it. Assigning to a key that already exists replaces the old value, which is forgotten. There is no separate "add" and "update" syntax for a single item. del removes a key and its value.

How to avoid KeyError

Reading a key that is not in the dictionary with square brackets raises an error:

>>> tel['irv']
Traceback (most recent call last):
  ...
KeyError: 'irv'

That output is from a dictionary that does not contain 'irv'. There are three ways to deal with it, depending on what you want to happen.

  • Check first. 'guido' in tel returns True or False, and 'jack' not in tel is the opposite test. Both look at keys only.
  • Use get(). tel.get('irv') returns None for a missing key, or a default you choose: tel.get('irv', 0). The documentation states that this method never raises a KeyError.
  • Use setdefault(). If the key exists it returns its value. If not, it inserts the key with the default you give and returns that default. This is useful when you build up a dictionary of lists, because one call both creates the empty list and hands it back.
groups = {}
groups.setdefault("fruit", []).append("apple")
groups.setdefault("fruit", []).append("pear")
print(groups)

Example output:

{'fruit': ['apple', 'pear']}

If you do want a missing key to be an error, plain d[key] is the right choice. It fails loudly at the point of the mistake, which is better than a None that travels further through your program. To handle the error explicitly, see Python try and except.

How to loop through a dictionary

Looping over a dictionary directly gives you its keys. To get the key and the value together, use items():

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave

The keys() and values() methods give you only one side. Calling list(d) returns the keys in insertion order, and sorted(d) returns them sorted:

>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']

Python 3.8 added reversed(d), which returns an iterator over the keys in reverse order. It is a shortcut for reversed(d.keys()).

Are dictionaries ordered?

Yes, by insertion order, and since Python 3.7 that is guaranteed by the language. In CPython 3.6 it was an implementation detail you should not have relied on. Updating the value of an existing key does not move it. A key added after a deletion goes to the end, as this example from the documentation shows:

>>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> d["one"] = 42
>>> del d["two"]
>>> d["two"] = None
>>> d
{'one': 42, 'three': 3, 'four': 4, 'two': None}

Dictionary comprehensions

A dictionary comprehension builds a dictionary from any key and value expressions, in the same way a list comprehension builds a list:

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

If you know the list version already, the syntax is the same except for the braces and the key: value pair at the front. See Python list comprehension for the filtering and nesting rules, which carry over.

How to merge two dictionaries

There are three ways, and the value from the second dictionary wins whenever both contain the same key.

>>> odds = {i: i**2 for i in (1, 3, 5)}
>>> evens = {i: i**2 for i in (2, 4, 6)}
>>> {**odds, **evens}
{1: 1, 3: 9, 5: 25, 2: 4, 4: 16, 6: 36}

The {**a, **b} form works on every Python 3 version that supports dictionary unpacking. From Python 3.9 you can also write d | other, which creates a new dictionary, and d |= other, which updates d in place. The in-place form accepts either a mapping or an iterable of key-value pairs, while | needs two dictionaries.

The older method is d.update(other). It changes d in place, returns None, and also accepts keyword arguments such as d.update(red=1, blue=2). A common mistake is to write merged = a.update(b) and end up with merged set to None.

Other methods worth knowing

MethodWhat it does
d.pop(key)Removes the key and returns its value. Raises KeyError if the key is missing, unless you pass a default: d.pop(key, None).
d.popitem()Removes and returns the last inserted (key, value) pair (LIFO order). Raises KeyError on an empty dictionary. LIFO order is guaranteed from Python 3.7.
d.copy()Returns a shallow copy. Nested lists or dictionaries inside are shared, not duplicated.
dict.fromkeys(keys, value)Builds a new dictionary with every key set to value, which defaults to None.

Be careful with fromkeys() and mutable values. All the values refer to a single object, so dict.fromkeys(["a", "b"], []) gives both keys the same list, and appending to one appears under the other. The documentation recommends a dictionary comprehension to get distinct values: {key: [] for key in ["a", "b"]}.

Dictionaries and JSON

A Python dictionary looks a lot like a JSON object, and the standard json module converts between them. If you are reading or writing JSON, json.load vs json.loads covers which function to use for files and which for strings.

If your dictionary is not behaving

  • TypeError: unhashable type: 'list'. You used a list, or a tuple containing a list, as a key. Convert the list to a tuple of immutable items first.
  • A key seems to disappear. Keys are unique, so a second assignment to the same key replaces the first. Strings that look equal but differ in case or trailing spaces are different keys.
  • Changing a dictionary while looping over it. Adding or removing keys during a loop over that same dictionary is an error. Loop over list(d.items()) if you need to change it as you go, or build a new dictionary with a comprehension.
  • A copy changes the original. copy() is shallow. If the values are lists or dictionaries, modify them through the copy and the original sees the change too.

Frequently asked questions

Are Python dictionaries ordered?
Yes. Since Python 3.7 a dictionary keeps its keys in insertion order, and that is part of the language. Changing the value of an existing key does not move it, while a key that is deleted and added again goes to the end. Before 3.7 the order was only an implementation detail of CPython 3.6.
What can be used as a dictionary key in Python?
Any immutable type works as a key: strings and numbers always do. A tuple works only if everything inside it is also immutable. Lists cannot be keys, because they can be changed in place.
What is the difference between d[key] and d.get(key)?
d[key] raises a KeyError when the key is missing. d.get(key) returns None instead, or the default value you pass as the second argument, and never raises KeyError.
How do I merge two dictionaries in Python?
On Python 3.9 or later use d | other to create a new merged dictionary, or d |= other to update d in place. On older versions use {**d, **other}. In every case the values from the second dictionary win when both have the same key.

Sources