Skip to content
Happy Programming Guide
Start learning
Python

Python Dictionaries Explained

Dictionaries store labelled values. Here is how to create, read, update and loop over them, plus how to avoid the KeyError that catches everyone.

A dictionary stores values with labels instead of positions. Where a list says “the item at position 2”, a dictionary says “the item called email“.

Python
person = {
    "name": "Ada",
    "age": 36,
    "city": "Lahore",
}

print(person["name"])   # Ada

Why not just use a list?#

Compare these two ways of holding the same information:

Python
person = ["Ada", 36, "Lahore"]      # what is position 1 again?
person = {"name": "Ada", "age": 36, "city": "Lahore"}   # obvious

Dictionaries are also fast to look up. Finding a key takes the same time whether the dictionary holds ten entries or a million.

Reading values safely#

Python
person = {"name": "Ada", "age": 36}

print(person["name"])              # Ada
print(person["email"])             # KeyError: 'email'

print(person.get("email"))         # None — no crash
print(person.get("email", "n/a"))  # n/a — with a fallback

Use square brackets when the key must exist and a missing one is a real bug. Use get() when it is genuinely optional.

Adding, updating and removing#

Python
person = {"name": "Ada"}

person["age"] = 36                     # add
person["name"] = "Ada Lovelace"        # update — same syntax
person.update({"city": "London", "age": 37})

del person["city"]
removed = person.pop("age")            # remove and return
print(person)

There is no separate “add” and “edit”. Assigning to a key creates it if it is missing and replaces it if it is not.

Checking what is there#

Python
if "email" in person:
    print(person["email"])

print(len(person))          # how many entries
print(list(person.keys()))  # ['name']

Looping#

Python
prices = {"pen": 50, "book": 300, "bag": 1200}

for item in prices:                 # keys
    print(item)

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

for item, price in prices.items():  # both — the one you want most often
    print(f"{item}: Rs {price}")

print(sum(prices.values()))         # 1550

Nesting#

Dictionaries can hold lists, and lists can hold dictionaries. This is exactly the shape of data you get back from most web APIs.

Python
students = [
    {"name": "Ada", "marks": [90, 85]},
    {"name": "Sam", "marks": [70, 78]},
]

for student in students:
    average = sum(student["marks"]) / len(student["marks"])
    print(f"{student['name']}: {average}")

Note the single quotes inside the f-string braces — you cannot reuse double quotes there.

Counting with a dictionary#

A classic use: tallying how often things appear.

Python
words = ["code", "test", "code", "ship", "code"]
counts = {}

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

print(counts)   # {'code': 3, 'test': 1, 'ship': 1}

Questions people ask#

Can a dictionary key be anything?

Keys must be unchangeable types — strings, numbers and tuples work; lists do not. Strings are by far the most common.

Are dictionaries ordered?

Since Python 3.7, they keep the order you inserted things in. Do not rely on it for anything important, but it makes printing predictable.

What happens if I use the same key twice?

The last one wins. Keys are unique — assigning again replaces the previous value.

How is this different from JSON?

JSON is a text format that looks almost identical. json.loads() turns JSON text into a Python dictionary, and json.dumps() goes the other way.

Where to go next#

Next lessonPython functions explained

Keep reading

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *