Python course · Module 4: Data structures · Lesson 17 of 63
Quick answer: A Python dictionary stores pairs of keys and values in curly brackets: prices = {"Pen": 60, "Notebook": 450}. You look up a value by its key, not by a position: prices["Pen"] gives 60. A missing key raises KeyError, while prices.get("Laptop", 0) returns a default instead. Add or change a value with prices["Ruler"] = 40, delete with del or pop(), and loop over keys and values together with for name, price in prices.items():.
In this lesson you will learn:
- how to create a Python dictionary and read values by key
- the difference between
d[key]andd.get(key), and how to avoidKeyError - how to add, update and delete pairs, and check keys with
in - how to loop with
keys(),values()anditems(), and why the order is kept - how to build nested dictionaries, like a small product catalogue
Before you start: finish Lesson 16, Python Tuples and Unpacking: One-Item Tuples, Star Unpacking and Swapping, because looping with items() uses tuple unpacking. You will also need for loops from Lesson 12, Python for Loops and range(): Lists, Strings and enumerate() and if from Lesson 11, Python if, elif and else Statements (and match). All examples were tested on Python 3.14.6 and behave the same on Python 3.15.2, the newest release on python.org.
Table of Contents
Create a dictionary
A list finds items by position (0, 1, 2…). A dictionary finds values by a key that you choose, such as a product name. Each pair is written key: value, and pairs are separated by commas.
prices = {"Notebook": 450, "Pen": 60, "Backpack": 3200}
empty = {}
product = dict(name="Pen", price=60, colour="Blue")
print(prices)
print(len(prices), len(empty))
print(type(prices))
print(product)
{'Notebook': 450, 'Pen': 60, 'Backpack': 3200}
3 0
<class 'dict'>
{'name': 'Pen', 'price': 60, 'colour': 'Blue'}
len() counts the pairs, so prices has 3. {} is an empty dictionary. The dict() function is another way to build one: each name=value becomes a pair with the name as a string key. The Python tutorial describes a dictionary as “a set of key: value pairs, with the requirement that the keys are unique (within one dictionary)”.
Read a value: [] vs get()
prices = {"Notebook": 450, "Pen": 60, "Backpack": 3200}
print(prices["Pen"])
print(prices.get("Pen"))
print(prices.get("Laptop"))
print(prices.get("Laptop", 0))
60
60
None
0
Both prices["Pen"] and prices.get("Pen") return 60. The difference shows up when the key is missing. get() returns None (from Lesson 8), or the default you pass as the second argument, here 0. Square brackets stop the program instead:
prices = {"Notebook": 450, "Pen": 60, "Backpack": 3200}
print(prices["Laptop"])
Traceback (most recent call last):
File "/home/learner/python-course/err1_keyerror.py", line 2, in <module>
print(prices["Laptop"])
~~~~~~^^^^^^^^^^
KeyError: 'Laptop'
The KeyError message shows the key that was not found. Keys are case sensitive, so prices["pen"] fails in the same way with KeyError: 'pen'. Which one should you use? Use [] when the key must be there, because a KeyError points you straight at a bug. Use get() when a missing key is normal, for example when a customer types any product name.
Check a key with in
in from Lesson 9, Python Operators: Comparison, Logical, is vs == and Precedence checks the keys of a dictionary:
prices = {"Notebook": 450, "Pen": 60, "Backpack": 3200}
print("Pen" in prices)
print("Laptop" in prices)
print(60 in prices)
item = "Laptop"
if item in prices:
print(item, "costs", prices[item])
else:
print(item, "is not in the shop.")
True
False
False
Laptop is not in the shop.
60 in prices is False even though 60 is a price: in looks only at keys. Checking with in before using [] is a safe pattern that never raises KeyError.
Add, update and delete
Assigning to a key adds the pair if the key is new, and replaces the value if the key already exists. update() does the same for several pairs at once.
prices = {"Notebook": 450, "Pen": 60}
prices["Ruler"] = 40
print(prices)
prices["Pen"] = 75
print(prices)
prices.update({"Pen": 70, "Eraser": 25})
print(prices)
{'Notebook': 450, 'Pen': 60, 'Ruler': 40}
{'Notebook': 450, 'Pen': 75, 'Ruler': 40}
{'Notebook': 450, 'Pen': 70, 'Ruler': 40, 'Eraser': 25}
There is no append() for dictionaries; prices["Ruler"] = 40 is how you add. update() changed "Pen" (the key existed) and added "Eraser" (a new key). To delete, use del or pop():
prices = {"Notebook": 450, "Pen": 70, "Ruler": 40, "Eraser": 25}
del prices["Ruler"]
print(prices)
removed = prices.pop("Eraser")
print("Removed price:", removed)
print(prices)
print(prices.pop("Laptop", "not found"))
{'Notebook': 450, 'Pen': 70, 'Eraser': 25}
Removed price: 25
{'Notebook': 450, 'Pen': 70}
not found
del prices["Ruler"] removes the pair. pop("Eraser") removes it and gives back the value, like pop() on a list. With a second argument, pop() returns that default when the key is missing. Without a default, both del and pop() raise KeyError for a missing key, as the Built-in Types page states.
Loop over a dictionary
A plain for loop over a dictionary gives you the keys. Use them to look up each value, or use the methods keys(), values() and items():
prices = {"Notebook": 450, "Pen": 60, "Backpack": 3200}
for name in prices:
print(name, "->", prices[name])
print(list(prices.keys()))
print(list(prices.values()))
print(list(prices.items()))
Notebook -> 450
Pen -> 60
Backpack -> 3200
['Notebook', 'Pen', 'Backpack']
[450, 60, 3200]
[('Notebook', 450), ('Pen', 60), ('Backpack', 3200)]
items() gives each pair as a tuple (key, value). The tutorial says that with items() “the key and corresponding value can be retrieved at the same time”. Unpack the tuple in the for line, exactly as you did with a list of tuples in Lesson 16:
prices = {"Notebook": 450, "Pen": 60, "Backpack": 3200}
total = 0
for name, price in prices.items():
print(f"{name:<10}{price:>6}")
total += price
print(f"{'Total':<10}{total:>6}")
Notebook 450
Pen 60
Backpack 3200
Total 3710
This is the most common way to loop over a dictionary. The :<10 and :>6 format specs come from Lesson 7, Python Strings and f-Strings: Quotes, Escapes and Formatting.
Dictionaries keep insertion order
Since Python 3.7, a dictionary remembers the order in which keys were added. The Built-in Types page says: “Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.” Here is each rule in action:
stock = {"Notebook": 12, "Pen": 40, "Backpack": 5}
stock["Pen"] = 35
print(stock)
del stock["Notebook"]
stock["Notebook"] = 20
print(stock)
duplicate = {"Pen": 60, "Pen": 75}
print(duplicate)
{'Notebook': 12, 'Pen': 35, 'Backpack': 5}
{'Pen': 35, 'Backpack': 5, 'Notebook': 20}
{'Pen': 75}
Changing "Pen" kept it in second place. Deleting "Notebook" and adding it again moved it to the end. The last example shows that keys are unique: when the same key is written twice, the language reference says “the final dictionary’s value for a given key will be the last one given”, so only "Pen": 75 is left.
What can be a key?
Strings and numbers are the usual keys. A tuple can be a key too, for example a pair of cities for delivery prices. A list cannot, because it can change:
delivery = {("Lahore", "Karachi"): 350, ("Lahore", "Multan"): 250}
print(delivery[("Lahore", "Multan")])
250
delivery = {["Lahore", "Karachi"]: 350}
Traceback (most recent call last):
File "/home/learner/python-course/err4_list_key.py", line 1, in <module>
delivery = {["Lahore", "Karachi"]: 350}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')
The Built-in Types page explains that values “containing lists, dictionaries or other mutable types” may not be used as keys. Python 3.14 added the first part of this message, “cannot use ‘list’ as a dict key”, as one of its improved error messages; on Python 3.13 we saw only TypeError: unhashable type: 'list'. Values have no such rule: a value can be anything, even a list or another dictionary.
Counting with get()
get() with a default of 0 is a classic way to count things:
orders = ["Pen", "Notebook", "Pen", "Ruler", "Pen", "Notebook"]
counts = {}
for item in orders:
counts[item] = counts.get(item, 0) + 1
print(counts)
{'Pen': 3, 'Notebook': 2, 'Ruler': 1}
The first time "Pen" appears, counts.get("Pen", 0) gives 0, so the count becomes 1. After that, get() returns the current count and the line adds 1. Without the default, the first lookup of each item would fail.
Nested dictionaries
A value can be another dictionary. This is how many programs store records, for example a product catalogue where each product code points to its details:
products = {
"P001": {"name": "Notebook", "price": 450, "stock": 12},
"P002": {"name": "Pen", "price": 60, "stock": 40},
"P003": {"name": "Backpack", "price": 3200, "stock": 5},
}
print(products["P002"]["name"])
print(products["P002"]["price"])
products["P003"]["stock"] -= 1
print(products["P003"])
for code, info in products.items():
print(f"{code}: {info['name']} costs {info['price']}, {info['stock']} in stock")
Pen
60
{'name': 'Backpack', 'price': 3200, 'stock': 4}
P001: Notebook costs 450, 12 in stock
P002: Pen costs 60, 40 in stock
P003: Backpack costs 3200, 4 in stock
Read products["P002"]["price"] from left to right: products["P002"] gives the inner dictionary for the pen, and ["price"] takes the price from it. -= 1 changes the stock inside the inner dictionary, one backpack sold. Inside the f-string we use single quotes, info['name'], so they are easy to tell apart from the double quotes around the f-string. (info["name"] also works inside it on Python 3.12 and newer, as What’s New in Python 3.12 explains, but mixing the two kinds of quotes is easier to read.)
Try it yourself
Exercise 1: Phone book
Make a dictionary with three names and phone numbers. Print one number, add a fourth person, then use get() to look up a name that is not there and print unknown instead of an error. Finally print how many contacts there are.
Exercise 2: Count the letters
Count how many times each letter appears in the word "banana" and print the dictionary.
Exercise 3: Stock value
Use the nested products dictionary from this lesson (with the original stock of 5 backpacks). Print the value of each product’s stock (price times stock) and the total value of all stock.
Solutions
Solution 1
phone_book = {"Ali": "0300-1111111", "Sara": "0321-2222222", "Hina": "0333-3333333"}
print(phone_book["Sara"])
phone_book["Omar"] = "0345-4444444"
print(phone_book.get("Bilal", "unknown"))
print(len(phone_book), "contacts")
0321-2222222
unknown
4 contacts
The numbers are strings because they contain a dash. get() with a default avoids the KeyError for "Bilal".
Solution 2
word = "banana"
letters = {}
for letter in word:
letters[letter] = letters.get(letter, 0) + 1
print(letters)
{'b': 1, 'a': 3, 'n': 2}
The same counting pattern as above; the keys appear in the order the letters were first seen.
Solution 3
products = {
"P001": {"name": "Notebook", "price": 450, "stock": 12},
"P002": {"name": "Pen", "price": 60, "stock": 40},
"P003": {"name": "Backpack", "price": 3200, "stock": 5},
}
total_value = 0
for code, info in products.items():
value = info["price"] * info["stock"]
print(f"{info['name']}: {value:,}")
total_value += value
print(f"Total stock value: {total_value:,} rupees")
Notebook: 5,400
Pen: 2,400
Backpack: 16,000
Total stock value: 23,800 rupees
items() gives each code with its inner dictionary, and info["price"] * info["stock"] is that product’s stock value.
Common mistakes
- Using [] for a key that may be missing.
prices["Laptop"]givesKeyError: 'Laptop'. Useprices.get("Laptop", 0)or check withinfirst. - Getting the case wrong.
"pen"and"Pen"are different keys, soprices["pen"]givesKeyError: 'pen'. - Forgetting items() in a loop.
for name, price in prices:loops over the keys only, and each key is a string, so Python tries to unpack"Notebook"into two names:ValueError: too many values to unpack (expected 2). Writeprices.items(). - Using a list as a key. It gives
TypeError: cannot use 'list' as a dict key (unhashable type: 'list'). Use a tuple. - Deleting keys while looping over the same dictionary.
for name in stock:withdel stock[name]inside givesRuntimeError: dictionary changed size during iteration. Loop over a copy of the keys instead:for name in list(stock):.
Frequently asked questions
How do I check if a key exists in a Python dictionary?
Use in: "Pen" in prices is True when "Pen" is a key. in checks keys only, not values; to search the values, use 60 in prices.values(). If you only need the value, prices.get("Pen") returns None when the key is missing.
What is the difference between get() and square brackets in a Python dictionary?
Both return the value for a key that exists. For a missing key, d[key] raises KeyError, while d.get(key) returns None, or the default you give as the second argument. The docs say get() “never raises a KeyError”.
Are Python dictionaries ordered?
Yes. Since Python 3.7, dictionaries keep keys in the order they were added, and looping, keys(), values() and items() all follow that order. Changing a value keeps the key in its place; a key deleted and added again goes to the end.
Summary
- A dictionary stores
key: valuepairs; keys are unique and must not be mutable, so use strings, numbers or tuples. d[key]raisesKeyErrorfor a missing key;d.get(key, default)returns the default instead.d[key] = valueadds or updates,update()does several at once, anddelorpop()deletes.inchecks keys;for key, value in d.items():loops over pairs in insertion order.- A value can be another dictionary; read nested values with
d["outer"]["inner"].
Next lesson
Next: Lesson 18, Python Sets.
Sources
- Data Structures: Dictionaries and Looping Techniques (Python tutorial)
- Built-in Types: Mapping types, dict (Python docs)
- Expressions: Dictionary displays (Python language reference)
- What’s New in Python 3.14: improved error messages (Python docs)
- What’s New in Python 3.12: quote reuse in f-strings, PEP 701 (Python docs)
- Python downloads page (python.org)





