Dictionaries in Python

Published by Brayan K

Store and access data using key-value pairs for fast and organized data management.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A dictionary looks values up by key

A dictionary is written in curly braces as pairs of a key, a colon and a value, separated by commas. Where a list takes a position in its square brackets, a dictionary takes a key:

person = {"name": "Ada", "age": 36, "city": "London"}
print(person["name"])
print(person["age"] + 1)
print(len(person))
print(person)

# ✅ Expected output:
# Ada
# 37
# 3
# {'name': 'Ada', 'age': 36, 'city': 'London'}

len() counts the pairs. Keys are usually strings, though numbers work too, and a value can be anything, a list or another dictionary included. A dictionary has no positions: person[0] looks for a key that is the number 0 and stops with KeyError: 0. Nor does a dot reach a key, as it does in JavaScript: person.name stops with AttributeError: 'dict' object has no attribute 'name'.

Leave out a colon and the program doesn't start: stops with SyntaxError: ':' expected after dictionary key. A comma in place of the colon is quieter. is a set, a collection of single values without keys, and the error only comes at the first lookup: TypeError: 'set' object is not subscriptable.

A missing key, and get()

Asking for a key the dictionary doesn't have stops the program, and the error names the key:

person = {"name": "Ada", "age": 36}
print(person["email"])

# ✅ Expected error:
# KeyError: 'email'

There are two ways to ask safely. in checks whether a key is there, and .get() returns the value, or None when the key is missing, or the default you give it:

person = {"name": "Ada", "age": 36}
print("email" in person, "name" in person, 36 in person)
print(person.get("name"))
print(person.get("email"))
print(person.get("email", "no email"))

# ✅ Expected output:
# False True False
# Ada
# None
# no email

in looks only at the keys, so 36 in person is False although 36 is one of the values. And the None from .get() can still stop the program a step later, when you calculate with it:

stock = {"apples": 12}
stock["pears"] = stock.get("pears") + 1

# ✅ Expected error:
# TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Give .get() a default that suits the calculation, here 0. That makes the usual way to count things:

votes = ["ana", "ben", "ana", "cara", "ana"]
counts = {}
for name in votes:
    counts[name] = counts.get(name, 0) + 1
print(counts)

# ✅ Expected output:
# {'ana': 3, 'ben': 1, 'cara': 1}

The first time a name comes up it has no entry yet, so counts.get(name, 0) gives 0 and the line stores 1. Each later time adds 1 to the count so far. Counter & defaultdict shows a ready-made counter that does this in one line.

Adding, changing and removing

Assigning to a key adds the pair when the key is new and replaces the value when it isn't, since a key can appear only once:

person = {"name": "Ada"}
person["age"] = 36
person["age"] = 37
person.update({"city": "London", "age": 38})
print(person)

age = person.pop("age")
del person["city"]
print(age, person)

# ✅ Expected output:
# {'name': 'Ada', 'age': 38, 'city': 'London'}
# 38 {'name': 'Ada'}

update() does the same for each pair of another dictionary, so "age" was replaced a second time. pop() removes a key and returns its value, and del removes it without returning anything. Both stop with a KeyError on a key that isn't there, unless you give pop() a default, as in person.pop("email", None). There's no append(): a dictionary grows by assigning to new keys.

| combines two dictionaries into a new one, and where both have a key, the right-hand one wins. It needs Python 3.9 or later; + doesn't work on dictionaries at all.

defaults = {"theme": "light", "size": 12}
chosen = {"size": 14}
settings = defaults | chosen
print(settings)
print(defaults)

# ✅ Expected output:
# {'theme': 'light', 'size': 14}
# {'theme': 'light', 'size': 12}

Looping: keys, values and items

A for loop over a dictionary gives its keys. .values() gives the values, and .items() gives each key with its value, a pair to unpack into two names:

prices = {"tea": 120, "coffee": 275, "cake": 340}

for name in prices:
    print(name)

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

for name, pence in prices.items():
    print(name, pence)

# ✅ Expected output:
# tea
# coffee
# cake
# 120
# 275
# 340
# tea 120
# coffee 275
# cake 340

Unpacking two names from the dictionary itself, without .items(), is a common slip:

prices = {"tea": 120, "coffee": 275}
for name, pence in prices:
    print(name, pence)

# ✅ Expected error:
# ValueError: too many values to unpack (expected 2)

The loop hands over each key, a string, and Python tries to split "tea" into two names. A key of exactly two characters would split without an error, into its two letters, which is harder still to spot. Removing keys while looping is the other trap:

stock = {"apples": 12, "pears": 0, "plums": 3}
for name in stock:
    if stock[name] == 0:
        del stock[name]

# ✅ Expected error:
# RuntimeError: dictionary changed size during iteration

A list would skip items without a word, as Loops - For and While showed; a dictionary refuses. Loop over a list of its keys, list(stock), made before the loop starts, and delete from the dictionary itself:

stock = {"apples": 12, "pears": 0, "plums": 3}
for name in list(stock):
    if stock[name] == 0:
        del stock[name]
print(stock)

# ✅ Expected output:
# {'apples': 12, 'plums': 3}

Order, and comparing dictionaries

Since Python 3.7, a dictionary keeps its keys in the order they were added, so printing and looping always go in that order. Order doesn't count when you compare two dictionaries, though:

a = {"x": 1, "y": 2}
b = {"y": 2, "x": 1}
print(a)
print(b)
print(a == b)

# ✅ Expected output:
# {'x': 1, 'y': 2}
# {'y': 2, 'x': 1}
# True

== asks whether both hold the same pairs. To go through a dictionary sorted by its values instead of in the order the keys arrived, you pass sorted() a key, which Sorting with sorted() & key covers.

What can be a key

Python finds a key through a number worked out from it, its hash, which is what keeps lookups fast however big the dictionary gets. A value that can change in place, like a list, could change that number after being stored, so a list has no hash at all. hash() asks for one:

print(hash("London") == hash("London"))
print(hash([51.5, -0.1]))

# ✅ Expected output:
# True

# ✅ Expected error:
# TypeError: unhashable type: 'list'

So Python won't take a list as a key: places[[51.5, -0.1]] = "London" stops with the same TypeError. From Python 3.14 the message says what the list was used for, cannot use 'list' as a dict key (unhashable type: 'list').

"Hashable" is the word for what a key must be. Strings, numbers, True and False, and tuples made of them all are. A tuple, from Tuples, is the usual way to key by two values at once:

places = {(51.5, -0.1): "London", (48.9, 2.4): "Paris"}
print(places[(48.9, 2.4)])

# ✅ Expected output:
# Paris

A list of dictionaries

Records with the same fields are usually kept as a list of dictionaries, one per record, and a value can itself be a list:

people = [
    {"name": "Ada", "langs": ["Python", "C"]},
    {"name": "Linus", "langs": ["C"]},
]
for person in people:
    print(person["name"], len(person["langs"]))
print(people[0]["langs"][1])

# ✅ Expected output:
# Ada 2
# Linus 1
# C

Read the last line from the left: people[0] is Ada's dictionary, ["langs"] her list, and [1] its second item. Data from websites usually arrives in this shape, as JSON, which Working with JSON turns into exactly these lists and dictionaries.

Where dictionaries go from here

Comprehensions build a dictionary from a loop in one line, and Dictionary Methods Deep Dive covers the rest of the methods, such as setdefault() and popitem().

Practice: a café price list

The first line looks up coffee. Fill the three blanks using the hints, in order: ask for juice without an error, add juice to the menu, and print every item with its price.

prices = {"tea": 120, "coffee": 275, "cake": 340}
print(prices["coffee"])
print(prices.___("juice", 0))

prices["juice"] = ___
for name, pence in prices.___():
    print(name, pence)

# 👉 replace ___ with get
# 👉 replace ___ with 199
# 👉 replace ___ with items

# ✅ Expected output:
# 275
# 0
# tea 120
# coffee 275
# cake 340
# juice 199

Juice prints as 0 before it's added: Python runs the lines in order, so the price list has no juice yet when .get() asks.

On your own: words by first letter

Group words = ["apple", "banana", "avocado", "cherry", "blueberry"] by their first letter: build a dictionary whose keys are letters and whose values are lists of the words starting with that letter, in their original order. A string indexes like a list, so word[0] is its first letter. Print the dictionary, then each letter with how many words it has: two for a and b, one for c. Then compare with this solution:

words = ["apple", "banana", "avocado", "cherry", "blueberry"]
groups = {}
for word in words:
    letter = word[0]
    if letter not in groups:
        groups[letter] = []
    groups[letter].append(word)

print(groups)
for letter, group in groups.items():
    print(letter, len(group))

# ✅ Expected output:
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
# a 2
# b 2
# c 1

A new letter gets an empty list first, and every word is then appended to its letter's list. defaultdict(list), from Counter & defaultdict, makes the empty list for you.

Practice quiz

person = {"name": "Ada"}. What does person["email"] do?

  • Returns None
  • Returns an empty string
  • Adds the key "email"
  • Stops with KeyError: 'email'

Answer: Stops with KeyError: 'email'. Square brackets need the key to exist. .get() is the way to ask without an error.

person has no "email" key. What does person.get("email", "none") return?

  • None
  • 'none'
  • A KeyError
  • ''

Answer: 'none'. .get() returns the default you give it when the key is missing.

prices = {"tea": 120, "cake": 340}. What does for x in prices: print(x) print?

  • tea, then cake
  • 120, then 340
  • ('tea', 120), then ('cake', 340)
  • An error

Answer: tea, then cake. Looping over a dictionary gives its keys. Use .values() or .items() for the rest.

counts = {}, then counts["a"] = counts.get("a", 0) + 1 runs twice. What is counts?

  • {'a': 1}
  • {'a': 0}
  • {'a': 2}
  • {'a': 1, 'a': 2}

Answer: {'a': 2}. The first run stores 0 + 1, and the second 1 + 1.

d = {"x": 1}, then d["x"] = 5. What is d?

  • {'x': 5}
  • {'x': 1, 'x': 5}
  • {'x': [1, 5]}
  • An error

Answer: {'x': 5}. A key appears only once, so assigning to an existing key replaces its value.

Which of these can't be a dictionary key?

  • "name"
  • 42
  • (1, 2)
  • [1, 2]

Answer: [1, 2]. A list can change in place, so it isn't hashable: using one as a key stops with a TypeError that says unhashable type: 'list'.

prices = {"tea": 120}. What does 120 in prices give?

  • True
  • False
  • 120
  • An error

Answer: False. in checks the keys, and 120 is a value.

What does {"x": 1, "y": 2} == {"y": 2, "x": 1} give?

  • False
  • An error
  • True
  • None

Answer: True. Two dictionaries are equal when they hold the same pairs, whatever their order.

Continue this course

Frequently asked questions

Does looking up a key get slower as a dictionary grows?

Not on average. Python finds a key through its hash, so a lookup usually takes about the same time with ten pairs or ten million. It slows down only when many keys share the same hash, which strings and numbers almost never do. Searching a list with in has to check its items one by one, which is why a dictionary, or a set, is the better choice for frequent lookups.

How do I find the key with the largest value?

max(counts, key=counts.get) goes through the keys and compares them by their values, so for {"ana": 3, "ben": 1} it gives "ana". The key= argument is explained in Lambda Functions.

Related lessons