Skip to main content
v2026.11,858 entries · CC-BY 4.0

What Is a Dictionary in Python? Keys, Values and Common Errors

A Python dictionary stores unique keys mapped to values. Create, read, update and loop over one, and fix KeyError and unhashable-key errors.

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.

  1. Create a dictionary. Write key: value pairs inside braces.
    samples = {"S01": 4.2, "S02": 3.9}
    print(samples)
    {'S01': 4.2, 'S02': 3.9}
  2. 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}
  3. Read a value. Index with the key, or use get to supply a default when the key may be missing. The reference says get returns the value for the key if it is in the dictionary, else the default (and None if you give none).
    print(samples["S01"])
    4.2
    print(samples.get("S09"))
    None
    print(samples.get("S09", "missing"))
    missing
  4. Test for a key. The tutorial uses in and not in.
    print("S02" in samples)
    True
  5. Delete an entry. del removes a pair; list(d) then returns the remaining keys in insertion order.
    del samples["S02"]
    print(list(samples))
    ['S01', 'S03']
  6. 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() and d.items() return views. The reference says that when the dictionary changes, the view reflects the change. Wrap in list(...) if you need a snapshot.
  • Merging. From Python 3.9, a | b returns a new dictionary, and where both have the same key the values of b take priority. a.update(b) changes a in place, overwrites shared keys, and returns None.
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

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about What Is a Dictionary in Python? Keys, Values and Common Errors

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →

Ask CASRAI · Regulatory Radar

Research-admin question? Get an answer that links its sources.

An AI assistant specialized in research administration. Every answer links its sources to check before you act. 2 questions free, no account. $29/month after.

  • Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.
  • Every answer numbers its sources and links each one, so you can check the source yourself.