Python Dictionaries

Store labelled data as key-value pairs, then read, update, loop through and nest dictionaries.

Lesson 20 of 107Intermediate18 min read

A list is great when items are in order and you look them up by position. But much of the data you'll handle has labels instead: a person has a name, an age and an email; a product has a price and a stock level; a country has a capital. For data like this, Python has the dictionary.

A dictionary stores key-value pairs. You look up a value by its key, the way you'd look up a word in a real dictionary to find its meaning. Keys are usually strings, and the values can be anything: numbers, text, lists or even other dictionaries.

Dictionaries are one of the most important tools in Python. JSON data from websites, settings files, database rows and counting problems all map naturally onto them. In this lesson you'll create dictionaries, read and change them safely, loop through them and nest them to describe more complex data.

Creating a dictionary and reading values

Write a dictionary with curly braces, putting a colon between each key and its value and commas between the pairs:

Python
student = {
    "name": "Maya",
    "age": 15,
    "subjects": ["maths", "art"],
}
print(student["name"])       # Maya
print(len(student))          # 3 pairs

Square brackets read a value by its key. If the key doesn't exist, Python raises a KeyError. When a key might be missing, use the get() method instead: student.get("email") returns None, and student.get("email", "not given") returns the default you choose.

Keys must be unique. If you write the same key twice, the later value wins. Keys also need to be immutable values such as strings, numbers or tuples, so a list can't be a key.

Adding, changing and removing

Dictionaries are mutable, so you can change them at any time:

CodeWhat it does
d["email"] = "m@x.com"Add a key, or replace its value if it exists
d.update({"age": 16, "year": 11})Add or replace several pairs at once
del d["age"]Remove a key (KeyError if missing)
d.pop("age", None)Remove a key and return its value, safely
"age" in dTrue if the key exists

Notice that in checks the keys, not the values. To check values, use "Maya" in d.values().

Looping through a dictionary

There are three views you can loop over:

Python
prices = {"tea": 2.5, "coffee": 3.2, "juice": 2.8}

for item in prices:              # keys
    print(item)

for price in prices.values():    # values
    print(price)

for item, price in prices.items():   # both
    print(f"{item}: {price}")

items() is the one you'll use most. Each pass gives you a key and its value, unpacked into two variables. Since Python 3.7, dictionaries keep the order in which keys were added, so loops always run in that order.

Counting and grouping with dictionaries

A very common pattern is counting how many times each thing appears. Start with an empty dictionary and add one each time you see a key:

Python
counts = {}
for colour in ["red", "blue", "red", "green", "red"]:
    counts[colour] = counts.get(colour, 0) + 1

counts.get(colour, 0) returns the current count, or 0 the first time a colour appears. After the loop, counts is {"red": 3, "blue": 1, "green": 1}. The same idea groups items: store a list for each key and append to it.

Sorting, merging and nested dictionaries

Dictionaries keep insertion order, but you can produce a sorted view whenever you need one. sorted() on items() gives a list of (key, value) pairs:

Python
scores = {"Ana": 82, "Ben": 91, "Cleo": 67}
by_score = sorted(scores.items(), key=lambda pair: pair[1], reverse=True)
print(by_score)   # [('Ben', 91), ('Ana', 82), ('Cleo', 67)]

The key function picks the value (pair[1]) as the thing to sort by. Use pair[0] to sort by key instead.

To combine two dictionaries, Python 3.9 and later offer the | operator. Keys in the right-hand dictionary win when both contain the same key. On older versions, use {**defaults, **user} or update().

Python
defaults = {"theme": "light", "font": 14}
user = {"theme": "dark"}
settings = defaults | user   # {'theme': 'dark', 'font': 14}

Nested dictionaries are read one key at a time from left to right: config["database"]["port"]. If an inner key might be missing, chain get() with an empty dictionary as the default: config.get("database", {}).get("port", 5432).

Python Dictionaries Syntax

Dictionary syntax

d = {"key1": value1, "key2": value2}
d["key1"]                # read (KeyError if missing)
d.get("key3", default)   # read safely
d["key3"] = value3       # add or change
del d["key1"]            # remove
for key, value in d.items():
    print(key, value)

Python Dictionaries Summary

  • A dictionary stores key-value pairs: {"key": value}.
  • Read with d["key"]; use d.get("key", default) when the key might be missing.
  • Assign to a key to add or change it; del and pop() remove keys.
  • in checks keys; loop with items() to get keys and values together.
  • Use d.get(k, 0) + 1 to count things, and lists of dictionaries for records.

Python Dictionaries Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A product record

Python
product = {"name": "Desk lamp", "price": 24.5, "stock": 22}

product["stock"] -= 1
product["colour"] = "black"
print(product)
print("Price:", product["price"])
print("Brand:", product.get("brand", "unknown"))
print("Has colour?", "colour" in product)
Output
{'name': 'Desk lamp', 'price': 24.5, 'stock': 21, 'colour': 'black'}
Price: 24.5
Brand: unknown
Has colour? True
Line-by-line explanation
  1. Line 3Change a value using its key.
  2. Line 4Assigning to a new key adds it to the end.
  3. Line 7get() returns the default because there's no "brand" key.
  4. Line 8in checks whether the key exists.
Example 2

Counting words

Python
text = "to be or not to be that is the question"
counts = {}

for word in text.split():
    counts[word] = counts.get(word, 0) + 1

for word, n in counts.items():
    if n > 1:
        print(f"{word}: {n}")
Output
to: 2
be: 2
Line-by-line explanation
  1. Line 2An empty dictionary to fill in.
  2. Line 5Add one to the word's count, starting from 0 the first time.
  3. Lines 7 to 9items() gives each word and its count; only repeated words are printed.
Example 3

A list of dictionaries

Python
students = [
    {"name": "Ana", "score": 82},
    {"name": "Ben", "score": 91},
    {"name": "Cleo", "score": 67},
]

best = max(students, key=lambda s: s["score"])
print("Top student:", best["name"])

for s in students:
    status = "pass" if s["score"] >= 70 else "retake"
    print(f"{s['name']:<5} {s['score']} {status}")
Output
Top student: Ben
Ana   82 pass
Ben   91 pass
Cleo  67 retake
Line-by-line explanation
  1. Lines 1 to 5One dictionary per student.
  2. Line 7key= tells max() to compare the students by their score.
  3. Line 12Inside an f-string, use single quotes for the key; :<5 pads the name to 5 characters.

Common Python Dictionaries Mistakes

Reading a key that might not exist

Don't
settings = {"theme": "dark"}
print(settings["language"])   # KeyError
Do
settings = {"theme": "dark"}
print(settings.get("language", "en"))

Expecting in to search the values

Don't
ages = {"Ana": 15, "Ben": 16}
print(15 in ages)    # False
Do
ages = {"Ana": 15, "Ben": 16}
print(15 in ages.values())   # True

Using a list as a key

Don't
places = {[51.5, -0.1]: "London"}
Do
places = {(51.5, -0.1): "London"}

Lists can change, so they can't be keys. A tuple, covered in the next lesson, works because it's immutable.

Python Dictionaries in Real Projects

Dictionaries in real programs

When a Python program calls a web API, such as a weather service, the JSON reply becomes nested dictionaries: data["current"]["temperature"]. Web frameworks pass dictionaries of values into page templates, configuration is often loaded into a dictionary of settings, and data scientists count categories with exactly the pattern you used above.

Python Dictionaries FAQ

When should I use a dictionary instead of a list?

Use a dictionary when you look things up by a name or ID, such as a product code or a username. Use a list when order matters and you work through items one by one or by position. Looking up a key in a dictionary is fast no matter how large it grows, while searching a list for a value gets slower as the list grows.

How do I find a key from its value?

Dictionaries are built for key-to-value lookups, so you have to search: next((k for k, v in d.items() if v == target), None) returns the first matching key, or None. If you do this often, build a reversed dictionary once with {v: k for k, v in d.items()}.

Can dictionary keys be numbers?

Yes. Any immutable value can be a key, including integers, floats, strings and tuples. Note that 1 and 1.0 count as the same key because they are equal. Lists, sets and dictionaries can't be keys because they can change.

Is there an easier way to count items than get(key, 0) + 1?

Yes. collections.Counter does it in one call: Counter(["red", "blue", "red"]) gives Counter({'red': 2, 'blue': 1}), and .most_common(3) returns the three most frequent items. Learning the manual pattern first helps you understand what Counter does for you.

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

d[key] raises a KeyError if the key is missing, which is right when the key must exist and a missing one is a bug. d.get(key) returns None, or a default you supply, which is right for optional data. Neither adds the key to the dictionary.

Python Dictionaries Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the code so it prints Lisbon.

capitals = {"Portugal": "Lisbon", "Spain": "Madrid"}
print(capitals[""])
Predict the outputeasy

What does this print?

d = {"a": 1, "b": 2}
d["a"] = 10
d["c"] = 3
print(len(d), d["a"])
Predict the outputmedium

What does this print?

stock = {"pens": 12}
print(stock.get("pencils", 0) + stock.get("pens", 0))
Multiple choicemedium

Which loop gives you both the key and the value?

Predict the outputhard

What does this print?

d = {"x": 1, "x": 2}
print(d)

Python Dictionaries Quiz

5 questions to check what you learned.

  1. Which brackets create a dictionary?

    • { }
    • [ ]
    • ( )
    • < >
  2. What happens when you read a missing key with square brackets?

    • It returns None
    • Python raises a KeyError
    • It returns 0
    • It adds the key
  3. What does d.get("age", 18) return if "age" isn't in d?

    • None
    • 18
    • "age"
    • A KeyError
  4. Which of these can be a dictionary key?

    • A list such as [1, 2]
    • Another dictionary
    • A set
    • A tuple such as (1, 2)
  5. In what order does a loop over a Python 3.7+ dictionary visit the keys?

    • Alphabetical order
    • Random order
    • The order the keys were added
    • Sorted by value