Python Dictionaries: What They Are and How to Use Them

By Dr. Zubair Khalid, DVM, MS, PhD ·

Python Dictionaries: What They Are and How to Use Them

A dict in Python is a built-in data structure that stores data as key-value pairs, where each key maps to exactly one value. You create one with curly braces, access values with square brackets or the get() method, and update values by assigning to an existing key. This article covers creation, access, updates, iteration and the mistakes that trip people up most often.

Quick Answer

  • A dict in Python is a mutable mapping of unique keys to values, written as {"key": value} [1].
  • Keys must be hashable and unique within one dictionary. Values can be anything [1].
  • Access a value with d[key], which raises KeyError if the key is missing, or with d.get(key), which returns None or a default instead [1].
  • Assigning to an existing key overwrites the old value. Assigning to a new key adds a pair [1].
  • Since Python 3.7, dictionaries preserve insertion order, so iteration follows the order you added items [1].

What Is a Python Dictionary?

A Python dictionary is a built-in container that stores data as key-value pairs, where each key maps to exactly one value. You write one with curly braces, like {"S-101": 12.4}, and you look up a value by its key rather than by its position. That single idea answers most of what people ask about this structure: it is a labeled lookup table, not a numbered list.

The keys must be unique within one dictionary and must be hashable, which means strings, numbers and tuples work but lists do not [1]. Values can be anything at all: numbers, text, lists, even other dictionaries. You read a value with square brackets, d["S-101"], which raises a KeyError if the key is missing, or with d.get("S-101"), which returns None or a default you choose instead of failing [1]. Writing d["S-102"] = 10.1 either adds a new pair or overwrites the value already stored under that key [1].

Dictionaries are mutable, so you can add, change and delete entries after you build one. Since Python 3.7 they also keep insertion order, so looping through a dictionary gives you the pairs in the order you added them [1]. That makes output predictable without any extra sorting.

TaskWhat to writeWhat happens
Build oned = {"a": 1, "b": 2}Creates two pairs
Read safelyd.get("c", 0)Returns 0 when "c" is absent
Add or changed["c"] = 3Adds "c" or overwrites it
Removedel d["a"]Drops that pair
Loopfor k, v in d.items()Visits each pair in order

The everyday use is lookup by a meaningful label: sample IDs, settings, counts by category. Reach for a list instead when position is what matters, and reach for a table structure when you need arithmetic across many records. A dictionary lives in memory and vanishes when your program ends, so it is a working tool, not a database.

What a Python Dictionary Means

In plain terms, a dict in Python is a labeled container. Instead of finding a value by its position, as you do in a list, you find it by a name you chose. If you have sample IDs and their measured concentrations, the sample ID is the key and the concentration is the value.

The precise definition: a dictionary is a mutable mapping object that associates hashable keys with arbitrary values, requires keys to be unique within the dictionary, and supports constant-time average lookup by key [1]. "Mutable" means you can add, change and remove entries after creation. "Hashable" means the key has a stable hash value, which is why strings, numbers and tuples work as keys but lists do not.

This structure is closely related to other Python containers. If you want an unordered collection of unique items with no values attached, see Python Sets: What They Are and How to Use Them. If you want to understand what kinds of objects can serve as keys or values, Python Data Types: Definition, Examples and How to Check Them covers that ground.

How It Works

A dictionary is a collection of pairs. Each pair has the form:

$$d[k] = v$$

where $d$ is the dictionary, $k$ is the key and $v$ is the value stored under that key. When you write d[k], Python hashes $k$, looks up the matching slot, and returns $v$. When you write d[k] = v, Python either updates the existing slot for $k$ or creates a new one.

The main operations are:

OperationSyntaxBehavior
Created = {"a": 1}Builds a dictionary with one pair
Readd["a"]Returns the value, raises KeyError if absent [1]
Safe readd.get("a")Returns None or a default if absent [1]
Add or updated["b"] = 2Creates the key or overwrites its value [1]
Deletedel d["a"]Removes the pair [1]
List keyslist(d)Returns keys in insertion order [1]
Iterated.items()Yields key-value pairs

You can also build a dictionary from a sequence of pairs using the dict() constructor, or with a dictionary comprehension when you are transforming existing data [1]. When your keys are simple strings, keyword arguments in the constructor are a compact alternative [1].

Worked Example

The dataset is a small lab record mapping sample IDs to measured concentrations in mg/L.

sample_idconcentration_mg_L
S-10112.4
S-1029.3
S-10315.2
S-10411.8

Start by creating the dictionary with four samples. The starting state holds 4 entries, with S-102 at 9.3.

Next, add a new sample S-105 with a concentration of 13.7. Assigning to a key that does not exist creates it, so len(samples) becomes 5.

Then update S-102. Its value was 9.3 and you assign 10.1. Because the key already exists, the old value is forgotten and replaced [1].

Finally, loop over the items and print each pair. The output follows insertion order, so S-105 appears last.

samples = {"S-101": 12.4, "S-102": 9.3, "S-103": 15.2, "S-104": 11.8}
samples["S-105"] = 13.7   # add a new sample
samples["S-102"] = 10.1   # update an existing value
for sid, conc in samples.items():
    print(f"{sid}: {conc} mg/L")
Output:
S-101: 12.4 mg/L
S-102: 10.1 mg/L
S-103: 15.2 mg/L
S-104: 11.8 mg/L
S-105: 13.7 mg/L

The dictionary went from 4 entries to 5, and S-102 moved from 9.3 to 10.1. Nothing else changed.

How to Interpret It

Read the result as a lookup table, not a sequence. The position of a pair tells you when it was inserted, not what it means. The key carries the meaning.

Two numbers matter in the worked example. The count went from 4 to 5, which confirms the addition. The S-102 value went from 9.3 to 10.1, which confirms the overwrite. If you expected 4 entries after adding a sample, you would have a bug in how you assigned the key.

When you print a dictionary, you see the current state, not a history. If you need to track changes over time, store the history separately, for example as a list of dictionaries or a table. This is the same discipline you apply when you document variables in a data dictionary for research teams, where each field name has one agreed meaning.

When to Use It (and when not to)

Use a dictionary when you need fast lookup by a meaningful label. Sample IDs, parameter names, configuration settings and counts by category are all natural fits. Use it when you need to attach metadata to an identifier, or when you want to count occurrences of things.

Avoid a dictionary when order is the primary meaning of your data and you will index by position. A list is clearer there. Avoid it when you need arithmetic across columns, filtering by condition, or joining two tables. That work belongs in a DataFrame, and Pandas in Python: What It Is and How to Use DataFrames explains how to move from raw dictionaries into that structure.

Also avoid using a dictionary as a database. It lives in memory, it disappears when the process ends, and it has no query language.

Dictionary vs List

FeatureDictionaryList
Access byKeyInteger position
Order meaningInsertion order [1]Positional order
Duplicate keysNot allowed [1]Duplicates allowed
Typical useLabeled lookupOrdered sequence
Missing accessKeyError [1]IndexError

The practical test is simple. If you would ask "what is the value for S-102," use a dictionary. If you would ask "what is the third item," use a list.

Common Mistakes

  • Using d[key] on a key that may not exist. This raises KeyError [1]. Use d.get(key) or d.get(key, default) instead.
  • Assuming a missing key returns None from subscript access. It does not. Only get() returns None by default [1].
  • Trying to use a list as a key. Lists are not hashable. Convert to a tuple if the contents are fixed.
  • Expecting duplicate keys to coexist. The second assignment overwrites the first, and the old value is forgotten [1].
  • Mutating a dictionary while iterating over it. Collect the keys you want to change first, then apply the changes.
  • Confusing dict.items() with dict.keys(). items() yields pairs, so you need two loop variables.

Limitations

A dictionary cannot enforce a schema. Nothing stops you from storing a string under one key and a number under another, and nothing warns you when a value has the wrong type or unit. Validation is your responsibility.

Dictionaries also do not support vectorized operations. You cannot add 1 to every value with a single expression the way you can with a numeric array or a DataFrame column. For anything beyond simple lookups and counts, you will usually convert to a table structure. Memory use is another constraint, since each entry carries key and value overhead, which matters when you hold millions of pairs.

Calculating an Average From a Dictionary

A common task is averaging the values stored in a dictionary, for example the mean concentration across samples. The pattern is to pull out the values, sum them, and divide by how many there are.

samples = {"S-101": 12.4, "S-102": 9.3, "S-103": 15.2, "S-104": 11.8}
values = samples.values()
average = sum(values) / len(values)
print(average)   # 12.175

values() gives you the numbers without the keys, sum() adds them, and len() counts them. Dividing gives the mean. If the dictionary might be empty, guard against division by zero first, because len() of an empty dictionary is 0 and dividing by it raises an error.

Averaging values that are themselves lists

Sometimes each key maps to several measurements, and you want the average of all of them. Flatten first, then average.

readings = {"S-101": [12.4, 12.9], "S-102": [9.3, 9.1]}
flat = [x for vals in readings.values() for x in vals]
average = sum(flat) / len(flat)

Averaging with a condition

To average only entries that meet a rule, filter the values before summing. For example, average only concentrations above 10:

kept = [v for v in samples.values() if v > 10]
average = sum(kept) / len(kept)

A frequent misconception

People sometimes try sum(samples) / len(samples). That adds the keys, not the values, and fails when keys are strings. Always call values() when you mean the stored numbers.

Dictionary Methods You Will Actually Use

The methods below cover most day to day work. Each one is a small tool with a clear job.

Reading and defaults

get(key, default) returns the value or your default without raising an error [1]. setdefault(key, default) goes further: it returns the value if the key exists, and if not it inserts the key with the default and returns that. This is handy for building grouped data.

groups = {}
for sid, conc in samples.items():
    band = "high" if conc > 12 else "low"
    groups.setdefault(band, []).append(sid)

Updating and merging

update(other) folds another dictionary into the current one, overwriting shared keys [1]. In modern Python you can also merge with the | operator, which produces a new dictionary instead of changing the original. The difference matters: update mutates, | copies.

Removing entries

pop(key) removes a pair and returns its value, and pop(key, default) returns the default instead of raising when the key is absent. popitem() removes and returns the last inserted pair. clear() empties the dictionary.

Viewing contents

keys(), values() and items() give you live views of the dictionary [1]. They reflect later changes, so if you add a pair after creating the view, the view shows it. Convert to a list if you need a fixed snapshot.

MethodPurposeReturns
getSafe readValue or default
setdefaultRead or insertValue
updateMerge in placeNone
popRemove by keyRemoved value
keys / values / itemsViewsLive views

Building Dictionaries From Other Data

Dictionaries rarely appear from nowhere. You usually build them from a list, a file or another structure.

From pairs and keyword arguments

The dict() constructor accepts a list of two-item tuples, or keyword arguments when keys are simple names [1].

d1 = dict([("a", 1), ("b", 2)])
d2 = dict(a=1, b=2)

With a comprehension

A dictionary comprehension transforms existing data in one line. The expression before the colon is the key, the one after is the value.

squared = {n: n * n for n in range(5)}   # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Counting occurrences

A classic pattern counts how often each item appears. get with a default of 0 keeps it short.

counts = {}
for word in ["a", "b", "a", "c", "a"]:
    counts[word] = counts.get(word, 0) + 1

Common misconception: nested dictionaries are not copies

If a value is itself a dictionary or list, assigning it to a second key does not copy it. Both keys point to the same object, so changing it through one key changes it through the other. Use a copy when you need independence.

Comparing Dictionaries With Other Structures

Choosing the right container saves rework later. The table below contrasts the main options.

StructureLookup byDuplicatesBest for
DictionaryKeyKeys unique [1]Labeled lookup, counts
ListPositionAllowedOrdered sequences
SetMembershipNot allowedUnique items, no values
DataFrameColumn and rowAllowedTabular math and joins

A dictionary answers "what is the value for this label." A list answers "what is at this position." A set answers "is this present." A DataFrame answers questions across many columns at once. If you find yourself looping over a dictionary to do column arithmetic, that is a signal to convert to a table.

Ordering and sorting

Insertion order is preserved, but it is not sorted order [1]. To get sorted output, apply sorted() to the keys or items.

for sid in sorted(samples):
    print(sid, samples[sid])

Membership and size

key in d checks for a key quickly and returns a boolean. len(d) gives the number of pairs. Neither tells you anything about values, so test values with a loop or a comprehension.

When a dictionary is the wrong tool

If you need to keep duplicate labels, a dictionary silently drops the earlier value [1]. If you need to preserve a strict sequence with repeats, use a list of pairs. If you need persistence across runs, write to a file or database instead of relying on an in-memory dictionary.

Frequently Asked Questions

How do I create an empty dictionary in Python?

Use a pair of braces with nothing inside, or call the constructor with no arguments. Both produce an empty dictionary you can fill later. The braces form is shorter and is the common choice in code.

What is the difference between d[key] and d.get(key)?

Subscript access returns the value and raises KeyError when the key is absent [1]. The get() method returns None by default, or a default you supply, when the key is absent [1]. Use get() whenever the key might not be there.

Can a dictionary have duplicate keys?

No. Keys are unique within one dictionary [1]. If you assign a value to a key that already exists, the old value is replaced. If you need multiple values per key, store a list as the value.

Does a Python dictionary keep its order?

Yes. Iterating a dictionary returns keys in insertion order, and list(d) gives you the keys in that same order [1]. If you need sorted output, apply sorted() to the keys.

How do I loop through a dictionary?

Call items() and unpack each pair into two variables, one for the key and one for the value. If you only need keys, iterate the dictionary directly. If you only need values, call values().

References

  1. 5. Data Structures, Python 3.14.8 documentation

Further Reading

Related Articles

Related articles