Learn / Beginner / Lesson 8

Dictionaries

11 min Tested on Python 3.15Updated By
In short

A dictionary (dict) stores key-value pairs, like {"name": "Asha", "age": 30}. You look values up by key (person["name"]), use .get() when a key might be missing, and loop over pairs with .items(). Dictionaries are how Python represents most real-world data, including JSON.

Creating and reading

Python
person = {"name": "Asha", "city": "Pune", "age": 30}
print(person["name"])
print(len(person))
print("city" in person)
Output
Asha
3
True

Keys are usually strings, and each key appears only once. Values can be anything: numbers, lists, even other dictionaries.

Missing keys and .get()

Python
person = {"name": "Asha"}
print(person.get("email"))
print(person.get("email", "not given"))

try:
    print(person["email"])
except KeyError as err:
    print("KeyError:", err)
Output
None
not given
KeyError: 'email'

Adding, changing and removing

Python
stock = {"apples": 10}
stock["pears"] = 4          # add
stock["apples"] -= 3        # change
stock.update({"kiwis": 6, "pears": 5})
removed = stock.pop("kiwis")
print(stock)
print(removed)
Output
{'apples': 7, 'pears': 5}
6

Looping over a dictionary

Python
prices = {"coffee": 3.2, "tea": 2.5, "cake": 4.0}
for item, price in prices.items():
    print(f"{item:<8}{price:>6.2f}")

print(list(prices.keys()))
print(sum(prices.values()))
Output
coffee    3.20
tea       2.50
cake      4.00
['coffee', 'tea', 'cake']
9.7

Dictionaries remember the order you inserted keys in, so loops always run in that order.

Counting things

Python
words = "the cat and the hat and the bat".split()
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)

from collections import Counter
print(Counter(words).most_common(2))
Output
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
[('the', 3), ('and', 2)]

Nested data, just like JSON

Python
order = {
    "id": 1042,
    "customer": {"name": "Ben", "country": "BE"},
    "items": [
        {"product": "mug", "qty": 2},
        {"product": "tea", "qty": 1},
    ],
}
print(order["customer"]["name"])
print(order["items"][0]["product"])
print(sum(i["qty"] for i in order["items"]))
Output
Ben
mug
3

API responses and config files almost always look like this. Read them by chaining keys and positions from the outside in.

Practice

Count the votes in votes = ["python", "rust", "python", "go", "python", "go"] with a dictionary, then print each language and its count on its own line, like python: 3, in the order they first appear.

Expected output:
python: 3
rust: 1
go: 2
Your code

Quick check

1. What does {"a": 1}.get("b", 0) return?

2. What do you loop over to get keys and values together?

3. After d = {"x": 1} and d["x"] = 5, how many keys does d have?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →