Written and maintained by CASRAI Editorial Board
Last updated
A dictionary in Python is a built-in collection of key: value pairs in which every key is unique within that dictionary. You look a value up by its key instead of by a position number, which makes it the natural structure for sample IDs mapped to measurements, gene names mapped to counts, or any lookup table in an analysis script. The behaviour described below is taken from the official Python documentation (tutorial section 5.5 and the Mapping Types section of the standard library reference, both checked 2026-10-29).
Not to be confused with a data dictionary, the document that describes the variables in a dataset. That is a different idea; see data dictionaries in research data management.
What it is used for in research
In a research script a dictionary is a lookup table. Typical uses are mapping a sample ID to a measurement, a participant code to a group label, or a category to a running count. The official tutorial describes the type as a set of key: value pairs with unique keys, and notes that a pair of braces creates an empty dictionary: {}.
Two properties matter most when you write analysis code:
- Keys must be unique. Assigning to an existing key replaces its value rather than adding a second entry.
- Keys must be hashable. The reference says values containing lists, dictionaries or other mutable types may not be used as keys. Strings and numbers can always be keys, and a list cannot.
If you are new to the surrounding language, the guide to Python modules and the guide to Python for exploratory data analysis cover the setting these examples run in.
Install or access
Nothing needs installing beyond Python itself: the dictionary is a built-in type, so there is no import line. Python is distributed from the official site, python.org. The behaviour of dictionaries has changed across versions, so check which Python your environment uses against the version labels in the table below.
| Behaviour | Python version |
|---|---|
| Insertion order kept (an implementation detail of CPython) | 3.6 |
| Insertion order guaranteed by the language | 3.7 |
reversed(d) supported |
3.8 |
d | other and d |= other merge operators |
3.9 |
Source: Python standard library reference, Mapping Types (dict), https://docs.python.org/3/library/stdtypes.html, checked 2026-10-29.
Step-by-step: create, read, change, delete and loop
Each step below uses a small table of sample IDs and measurements. The printed output is shown exactly as the interpreter prints it.
- Create a dictionary. Write key: value pairs inside braces.
samples = {"S01": 4.2, "S02": 3.9} print(samples) {'S01': 4.2, 'S02': 3.9} - Add or replace an entry. Assign to a key. A new key is added; an existing key is overwritten.
samples["S03"] = 5.1 print(samples) {'S01': 4.2, 'S02': 3.9, 'S03': 5.1} - Read a value. Index with the key, or use
getto supply a default when the key may be missing. The reference saysgetreturns the value for the key if it is in the dictionary, else the default (andNoneif you give none).print(samples["S01"]) 4.2 print(samples.get("S09")) None print(samples.get("S09", "missing")) missing - Test for a key. The tutorial uses
inandnot in.print("S02" in samples) True - Delete an entry.
delremoves a pair;list(d)then returns the remaining keys in insertion order.del samples["S02"] print(list(samples)) ['S01', 'S03'] - Loop over keys and values. Use
items(), as the tutorial does.for sid, value in samples.items(): print(sid, value) S01 4.2 S03 5.1
Counting with get, and building with a comprehension
Two patterns cover much of everyday analysis code. The first counts how often each label occurs, using get with a default of 0 so the first occurrence needs no special case:
labels = ["control", "treated", "control", "control", "treated"]
counts = {}
for g in labels:
counts[g] = counts.get(g, 0) + 1
print(counts)
{'control': 3, 'treated': 2}
The second builds a dictionary from an expression. The tutorial’s own example squares three numbers:
{x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
The standard library reference also documents setdefault, which returns the value if the key is present and otherwise inserts the key with a default (None unless you pass one) and returns it. For another everyday Python task in analysis scripts, see train-test split in Python.
Output and how to read it
- Order. Printing a dictionary shows entries in insertion order. The reference states that updating an existing key does not change its order, and that a key added after a deletion is inserted at the end. This is guaranteed from Python 3.7. Do not rely on it in code that must also run on older interpreters.
- Sorted keys.
sorted(d)returns the keys sorted, which is how you get a stable listing for a report or a figure legend. - Views are live.
d.keys(),d.values()andd.items()return views. The reference says that when the dictionary changes, the view reflects the change. Wrap inlist(...)if you need a snapshot. - Merging. From Python 3.9,
a | breturns a new dictionary, and where both have the same key the values ofbtake priority.a.update(b)changesain place, overwrites shared keys, and returnsNone.
a = {"S01": 4.2, "S02": 3.9}
b = {"S02": 4.0, "S04": 6.3}
print(a | b)
{'S01': 4.2, 'S02': 4.0, 'S04': 6.3}
print(a.update(b))
None
print(a)
{'S01': 4.2, 'S02': 4.0, 'S04': 6.3}
Troubleshooting
KeyError when reading a missing key
Indexing with a key that is not present raises KeyError. Use get when absence is expected, or test with in first. pop behaves the same way: the reference says that if the key is absent and no default is given, a KeyError is raised, so give a default (a.pop("S99", None) returns None) when the key may not exist.
a["S99"]
KeyError: 'S99'
TypeError: unhashable type
A list cannot be a key, because keys must be hashable. Convert it to something immutable, such as a tuple of strings or numbers (the tutorial allows tuples that contain only strings, numbers or tuples), or use a different key.
{[1, 2]: "x"}
TypeError: unhashable type: 'list'
A value disappeared after assigning
Keys are unique, so assigning to an existing key silently replaces its value. When combining two sources, decide which one should win: with | and update the second operand takes priority.
The result of update is None
update changes the dictionary in place and returns None. Writing merged = a.update(b) leaves merged as None.
The order is not what you expected on another machine
Insertion order is guaranteed from Python 3.7 only. If an older interpreter is in use, sort explicitly with sorted(d).
Free alternatives and equivalent forms
The dictionary is part of Python, so there is nothing separate to obtain. The documentation shows several equivalent ways to build the same dictionary:
| Form | Example from the Python tutorial |
|---|---|
| Braces with key: value pairs | {'sape': 4139, 'guido': 4127, 'jack': 4098} |
dict() from a list of key-value pairs |
dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) gives {'sape': 4139, 'guido': 4127, 'jack': 4098} |
| Dictionary comprehension | {x: x**2 for x in (2, 4, 6)} gives {2: 4, 4: 16, 6: 36} |
Source: Python tutorial, section 5.5 Dictionaries, docs.python.org/3/tutorial/datastructures.html, checked 2026-10-29. For unit-testing code that builds and transforms dictionaries, see the guide to unit testing.
FAQ
What is a dictionary in Python?
A built-in collection of key: value pairs with unique keys. You retrieve a value by its key rather than by a position. An empty dictionary is written {}.
Can a dictionary have duplicate keys?
No. Keys are unique within one dictionary, so assigning to an existing key replaces its value.
What can be a dictionary key?
Any hashable value. Strings and numbers always work; lists, dictionaries and other mutable types cannot be keys.
Are Python dictionaries ordered?
Yes, by insertion order, guaranteed from Python 3.7 (it was a CPython implementation detail from 3.6). Updating an existing key does not change its position.
How do I avoid a KeyError?
Use d.get(key, default), test key in d first, or pass a default to pop.
Is a Python dictionary the same as a data dictionary?
No. A Python dictionary is a data structure in code; a data dictionary documents the variables of a dataset. See data dictionaries in research data management.
Sources
- Python Software Foundation, The Python Tutorial, section 5.5 Dictionaries: https://docs.python.org/3/tutorial/datastructures.html (checked 2026-10-29).
- Python Software Foundation, The Python Standard Library, Built-in Types, Mapping Types (dict): https://docs.python.org/3/library/stdtypes.html (checked 2026-10-29).








