Python Programming · Foundations

Dictionaries

Want it in plain words first? Jump to Eli explains — the same idea, no jargon.
On this page 9 sections
  1. In 30 seconds
  2. Why this matters
  3. The college version
  4. Eli explains
  5. Worked example
  6. Key takeaway
  7. Quick check
  8. Study tools
  9. Sources & references

In 30 seconds

A Python dictionary is a mutable from unique, keys to values. Write a literal with braces and key-value pairs, such as {"apples": 3}. Use a in square brackets to retrieve or set its . Assigning with an existing key replaces that key's value; assigning with a new key adds a pair. Dictionaries preserve , but their main idea is lookup by a meaningful key rather than position.

Why this matters

Many programs need to connect a label to information: a course code to a title, a username to preferences, or a product code to available stock. A dictionary makes that relationship explicit. It also develops useful habits for later programming: choosing stable keys, handling missing information deliberately, and knowing whether an operation adds a record or updates one. These habits transfer to JSON-like data, configuration, and data analysis.

The college version

Mapping names to information

A Python dictionary, usually called a dict, stores associations rather than a numbered sequence. Each association has a key and a value. In {"course": "CS101", "credits": 3}, "course" is a key whose value is "CS101"; "credits" is another key whose value is 3. Braces make a dictionary literal, and an empty dictionary is {}. The standard documentation describes a dictionary as a mutable mapping: it maps a key to an arbitrary object. Values therefore do not all need to have the same type, even though a clear program commonly uses a predictable shape. The important constraint is on keys. A key must be hashable, which excludes mutable containers such as lists and dictionaries. Strings, integers, and tuples made entirely from suitable contents are common keys. A dictionary has one current value for each key. Writing a repeated key in a literal or assigning to an already present key does not make a second entry; the later value replaces the earlier association. Python also treats equal keys as the same entry: 1, 1.0, and True compare equal, so using them as keys can address one shared entry. That is a reason to choose key types deliberately.

Lookup, missing keys, and deliberate updates

Subscription uses square brackets with a key. If stock = {"apples": 3}, then stock["apples"] evaluates to 3. The same syntax on the left of assignment changes the mapping: stock["apples"] = 4 updates the existing value, while stock["pears"] = 2 adds a new . Direct lookup is appropriate when a missing key signals a mistake or a required condition; stock["bananas"] raises KeyError if that key is absent. When absence is expected, stock.get("bananas") returns None, and stock.get("bananas", 0) supplies a chosen fallback. That distinction matters: a fallback is not proof that the key was present. Use key in stock when the program needs to test membership explicitly. Dictionaries also provide views through keys(), values(), and items(). An item is a two-part key-value pair, which is convenient when a loop needs both pieces. This lesson does not cover loops; the essential point is that the key determines which value is retrieved or changed.

Order, equality, and a useful trace

Modern Python dictionaries preserve insertion order. If keys are first added as "apples", then "pears", then "oranges", iterating over the dictionary or applying list(stock) yields those keys in that order. Updating stock["pears"] changes its value but does not move that key to the end. Deleting a key and adding it again is a new insertion, so it appears later. This ordering is useful for predictable display and traces, but it should not obscure the mapping idea: dictionary equality is based on having the same key-value pairs, regardless of their order. Thus two dictionaries can compare equal even if their pairs were inserted in different orders. A dictionary is mutable, so methods and assignments can change an existing object. Passing one to later code therefore needs the same care as passing other mutable collections: that code can observe or change the mapping unless the program deliberately makes a separate copy. That concern is separate from insertion order and is a reason to state clearly which part of a program owns an update. A small trace makes the rules concrete. Start with stock = {"apples": 3, "pears": 1}. Add two to pears with stock["pears"] += 2, then set stock["oranges"] = 4. The result is {"apples": 3, "pears": 3, "oranges": 4}; the pears association was updated, and oranges was inserted last. A request for stock.get("bananas", 0) returns 0 without adding bananas. Choosing between a required lookup, a tested lookup, and a fallback makes code state its expectations clearly.

Choosing a clear dictionary shape

A dictionary is easiest to use when its keys have a single stated meaning. For example, a stock mapping can use product names as keys and counts as values. Mixing unrelated meanings into the same mapping makes later lookup unclear, even though Python technically permits values of different types. Before adding a key, decide what it identifies and what a missing key means. That small design step prevents a program from confusing an unknown record with a known record whose value is zero or None.

Eli, the EliExplains learning guide

Eli explains

The same idea, in plain words

Explain it like I’m 10

Think of a dictionary as a row of labeled cubbies. Instead of saying "give me cubby number 2," you can say "give me the cubby labeled apples." Inside that cubby is a value, perhaps the number 3. A dictionary keeps the label together with what it points to. You can put in a new labeled cubby or replace what is in one that already has that label.

The label has to be something dependable. A string like "apples" stays the same, so it works well. A list can be changed, so Python does not allow it as a dictionary key. If you ask for a label that was never added, square-bracket lookup complains with KeyError. get() is the polite alternative when an empty cubby is normal: it can return None or a fallback value.

Python remembers the order labels were first added, which helps when showing the dictionary. But the labels are still for finding values, not positions like the numbered slots in a list.

Picture it like this

A dictionary is like labeled cubbies: each label identifies one place, and each place holds its associated information.

Where the picture stops working

A Python dictionary is not a physical cabinet. Its lookup rules depend on hashable keys, equal keys can refer to the same entry, and stored values may be any Python objects.

Worked example

Run this Python 3 code:

stock = {"apples": 3, "pears": 1}
stock["pears"] += 2
stock["oranges"] = 4
print(stock)
print(stock.get("bananas", 0))
print(list(stock))

It prints {'apples': 3, 'pears': 3, 'oranges': 4}, then 0, then ['apples', 'pears', 'oranges']. The pears key already existed, so its value changed from 1 to 3 without changing its position. Oranges was new, so it was added at the end of insertion order. get supplied a fallback for an absent key and did not insert bananas.

Key takeaway

A dictionary maps unique hashable keys to values. Use direct lookup for required keys and get or membership testing when absence is expected; assignment either updates a key or inserts a new one.

Quick check

3 questions here, of 5 in this lesson’s practice set. Answers stay hidden until you check.

Question 1 of 3foundational

What is required of a Python dictionary key?

Choose an answer, then check it.
Question 2 of 3intermediate

After scores = {"Ada": 8} and scores["Ada"] = 10, what is scores["Ada"]?

Choose an answer, then check it.
Question 3 of 3intermediate

Which expression returns 0 rather than raising an exception when "late" is not a key in attendance?

Choose an answer, then check it.
Practice all 5

Keep learning

Ready to build on this? Continue to the next lesson.

Practice this lesson
Study tools & related lessonsYou’ll learn to · Common mistakes · Easily confused · Key vocabulary · Related

You’ll learn to

  • Define a dictionary as a mutable mapping of unique keys to values.
  • Create and update a dictionary with literal and subscription syntax.
  • Distinguish direct lookup from get() when a key may be absent.
  • Explain why dictionary keys must be hashable and unique.
  • Apply insertion-order and update behavior to trace a small program.

Common mistakes

  • Using a list as a dictionary key.

    Use a hashable key such as a string, integer, or appropriate tuple; lists are mutable and cannot be keys.

  • Expecting a repeated key to create two entries.

    A dictionary has one association per key; a later assignment replaces that key's value.

  • Using direct lookup when absence is normal.

    Use get with an appropriate default, or test membership with in, when the key may be missing.

  • Treating insertion order as numeric indexing.

    Use keys to retrieve values; order is preserved for iteration and display, not a substitute for positional access.

Easily confused

stock["bananas"] vs. stock.get("bananas", 0)

The first raises KeyError when bananas is absent; the second returns the supplied fallback without inserting a key.

stock["pears"] = 3 vs. stock["oranges"] = 4

The first updates an existing association; the second adds a new key-value pair.

Key vocabulary

dictionary (dict)
A mutable Python mapping that associates unique hashable keys with values.
mapping
A collection that retrieves a value by its associated key rather than by a numeric position.
key
A hashable value used to locate one association in a dictionary.
value
The object associated with a particular dictionary key.
key-value pair
One association consisting of a key and its value.
hashable
Suitable for use as a dictionary key because its hash value remains usable during its lifetime.
KeyError
The exception raised by direct dictionary subscription when the requested key is absent.
insertion order
The order in which keys were added to a dictionary; Python dictionaries preserve it.

Sources & references

  1. Mapping Types — dict — Python 3 documentation — Python Software Foundation
  2. 5. Data Structures — The Python Standard Library Documentation — Python Software Foundation

EliExplains lessons are original prose written from the open, credible references above. See Copyright & Licensing.

Researched 2026-08-19

Educational content only. It is not medical, legal or professional advice. Found an error? Tell us.