Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 149 ยท Data Structures

Dictionaries

Learn Python dictionaries, the key-value store behind most Python code. Create them, read and change values, delete keys, loop over items and rely on their order.

A dictionary (type dict) stores pairs of keys and values. Instead of finding things by position, like a list does, you find them by a meaningful key: a word gives you its definition, a username gives you a profile, a product code gives you a price. If lists are numbered shelves, dictionaries are labeled drawers.

Dictionaries are probably the single most important data structure in Python. JSON data from web APIs turns into dictionaries, configuration lives in them, and Python itself uses them internally to store variables and object attributes. This lesson covers the core skills: creating dictionaries, reading values, adding, changing and deleting entries, and looping over them. The next lesson, Dictionary Methods, goes deeper into the toolbox.

Creating a dictionary

Write a dictionary with curly braces. Each entry is key: value, and entries are separated by commas:

Python A first dictionary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Values can be anything: numbers, strings, lists, other dictionaries, even functions. Keys are more restricted: they must be hashable, which means immutable values such as strings, numbers, booleans or tuples of those. Each key appears only once. If you write the same key twice, the last value wins.

Python
grid = {(0, 0): "start", (3, 4): "goal"}   # tuple keys are fine
broken = {["a", "b"]: 1}                   # TypeError: a list is unhashable
dupes = {"x": 1, "x": 2}                    # {'x': 2}

Building from pairs

dict() also accepts a sequence of two-item pairs, which pairs nicely with zip():

Python
names = ["Ana", "Ben", "Cleo"]
ages = [31, 27, 45]
people = dict(zip(names, ages))   # {'Ana': 31, 'Ben': 27, 'Cleo': 45}

Reading values

Use square brackets with a key to get its value. Asking for a key that doesn't exist raises a KeyError, so check first with in, or use get(), which returns a fallback instead:

Python Looking things up

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that in looks at keys only. 12 in stock is False even though 12 is one of the values. To search values, use 12 in stock.values().

Tip: Use d[key] when the key must be there and a missing key is a bug you want to see. Use d.get(key, default) when a missing key is a normal situation.

Adding, changing and deleting

Dictionaries are mutable. Assigning to a key adds it if it's new and replaces the value if it already exists. There's no separate "insert" operation:

Python Changing a dictionary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

del d[key] raises a KeyError if the key is missing, just like reading it would. pop(key, default) is the forgiving alternative, and it also hands you the removed value.

Counting with a dictionary

A classic pattern combines get() with assignment to count things:

Python Counting words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

On the first sighting of a word, counts.get(word, 0) returns 0, so the count becomes 1. After that it returns the current count. max(counts, key=counts.get) finds the key with the biggest value. Python's collections module has a Counter class that does all of this for you, but the pattern is worth knowing by heart.

Looping over a dictionary

Looping over a dictionary directly gives you its keys. Three methods give you other views:

  • d.keys() โ€“ the keys
  • d.values() โ€“ the values
  • d.items() โ€“ (key, value) pairs, ready for unpacking
Python Iterating

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

items() is the loop you'll write most often. Unpacking each pair into two names, for item, price in ..., keeps the loop body readable.

Warning: Don't add or delete keys while looping over a dictionary. Python raises RuntimeError: dictionary changed size during iteration. Loop over a copy instead, such as for key in list(d):, or build a new dictionary.

Dictionaries keep insertion order

Since Python 3.7, dictionaries are guaranteed to remember the order in which keys were first inserted. Loops, print(), keys() and items() all follow that order. Replacing a value keeps the key's original position; deleting a key and adding it again moves it to the end.

Python Order is preserved

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two dictionaries with the same pairs are still equal (==) even if their order differs. Order affects iteration, not equality.

When to reach for a dictionary

A useful habit is to ask how you'll find things in your data. If the answer is "by position" (the first item, the next item, the last ten), a list fits. If the answer is "by some name or ID", a dictionary fits, and it fits much better than a list of pairs you'd have to search.

Looking up a key in a dictionary is fast no matter how many entries it holds, because Python uses the key's hash to jump straight to the right slot, just as sets do. Searching a list for a matching name means checking items one by one. With a few items you won't notice; with a hundred thousand customers, you will.

Dictionaries also make code more readable. user["email"] says what you're getting, while user[3] forces the reader to remember what position 3 holds. When each record has the same fixed set of fields, a dictionary is a fine start, and later you can upgrade to data classes for even clearer code.

Nested dictionaries

Values can be dictionaries or lists themselves, which is how you represent structured data such as a JSON response:

Python Nested data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read nested data one step at a time, left to right: library["books"] is a list, [1] is its second item, a dictionary, and ["title"] is a value inside it. Notice the f-string uses single quotes inside (book['title']) because the string itself uses double quotes. You'll load data like this from files in Working with JSON.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With d = {"a": 1, "b": 2}, what does "1" in d and 1 in d return?

    in checks keys only. The keys are "a" and "b", so both tests are False. Use 1 in d.values() to search values.
  2. 2. What happens when you read d["missing"] and the key doesn't exist?

    Square brackets raise KeyError for missing keys. d.get("missing") would return None instead.
  3. 3. Which of these can NOT be a dictionary key?

    Keys must be hashable. Lists are mutable, so they're unhashable; tuples, strings and numbers are fine.
  4. 4. Which loop gives you both the key and the value on each step?

    items() yields (key, value) pairs that you unpack into two names. Looping over d itself yields only keys.
  5. 5. d = {"x": 1} then d["y"] = 2 then d["x"] = 3. What is list(d)?

    Dictionaries keep insertion order, and updating an existing key keeps its original position.

Summary

  • A dictionary maps unique, hashable keys to values: {"France": "Paris"}.
  • Read with d[key] (raises KeyError if missing) or d.get(key, default); test keys with in.
  • Assign d[key] = value to add or replace; remove with del d[key] or d.pop(key, default).
  • Loop over keys directly, or use keys(), values() and especially items().
  • Dictionaries keep insertion order; never change their size while looping over them.
  • Values can be lists or other dictionaries, which is how structured data like JSON is represented.

Next: Dictionary Methods, where you'll use get, setdefault, update and the | merge operator like a pro.