Python Dictionaries Explained With Simple Examples
A beginner guide to Python dictionaries, covering keys and values, adding and deleting items, get() versus KeyError, looping, and counting things.
A list is great when order is what matters: first task, second task, third task. But a lot of real information is better described by name. A price belongs to a product. A phone number belongs to a person. A setting belongs to a setting name. For that, Python has the dictionary. Every example below was run in Python 3.13, and the output shown is what it printed.
What a dictionary is
The official Python tutorial describes a dictionary as a set of key: value pairs, with the requirement that keys are unique within one dictionary. Instead of looking items up by position (0, 1, 2), you look them up by key.
You write a dictionary with curly braces, a colon between each key and its value, and commas between pairs:
prices = {"coffee": 3.50, "bagel": 2.25}
prices["muffin"] = 2.75
print(prices)
print(prices["coffee"])
Output:
{'coffee': 3.5, 'bagel': 2.25, 'muffin': 2.75}
3.5
Square brackets with a key read a value. The same square brackets with = add a new pair. If the key already exists, assigning replaces the old value. The tutorial is direct about it: if you store using a key that is already in use, the old value is forgotten.
prices["coffee"] = 3.75
print(prices["coffee"])
Output:
3.75
Looking up a key that is not there
Ask for a key that does not exist with square brackets and Python stops with an error:
prices["tea"]
KeyError: 'tea'
The tutorial recommends the get() method when a key might be missing. It returns None instead of raising an error, or a default value you choose:
print(prices.get("tea"))
print(prices.get("tea", 0))
Output:
None
0
To check first, use in, which tests whether a key is in the dictionary:
print("bagel" in prices, "tea" in prices)
Output:
True False
Deleting, listing, and counting keys
del removes a pair. list() gives you the keys in the order they were added, and sorted() gives them alphabetically, both of which the tutorial describes.
del prices["bagel"]
print(prices)
print(list(prices))
print(sorted(prices))
print(len(prices))
Output:
{'coffee': 3.75, 'muffin': 2.75}
['coffee', 'muffin']
['coffee', 'muffin']
2
Looping through keys and values together
The tutorial's Looping Techniques section shows items(), which hands you each key and its value at the same time:
for item, price in prices.items():
print(f"{item}: ${price:.2f}")
Output:
coffee: $3.75
muffin: $2.75
The f before the string makes it an f-string, which the tutorial's Input and Output chapter explains: expressions inside curly braces are filled in, and :.2f formats the number with two decimal places. That is why 3.75 prints as a price.
A practical pattern: counting things
Counting is one of the most common jobs for a dictionary. Suppose you have a list of orders and want to know how many of each item were ordered.
order = ["coffee", "muffin", "coffee", "tea", "coffee"]
counts = {}
for item in order:
counts[item] = counts.get(item, 0) + 1
print(counts)
Output:
{'coffee': 3, 'muffin': 1, 'tea': 1}
Read the middle line slowly. counts.get(item, 0) returns the current count, or 0 the first time an item appears. Adding 1 and storing it back updates the count. No KeyError, no special case for the first time.
The same get() trick lets you total the order even though "tea" has no price:
total = 0
for item in order:
total += prices.get(item, 0)
print(total)
Output:
14.0
That is three coffees at 3.75 (11.25) plus one muffin at 2.75, with tea counted as 0.
Values can be anything, keys cannot
A value can be any type, including a list or another dictionary:
employee = {"name": "Rosa", "skills": ["Excel", "SQL"], "manager": {"name": "Tom"}}
print(employee["skills"][1])
print(employee["manager"]["name"])
Output:
SQL
Tom
Keys are stricter. The tutorial explains that keys can be any immutable type: strings and numbers always work, but lists cannot be keys because lists can be changed in place. Trying it gives an error:
d = {["a"]: 1}
TypeError: unhashable type: 'list'
The exact wording of error messages can differ slightly between Python versions, but the error type stays the same.
Key takeaways
- A dictionary stores unique keys, each paired with a value, and you look values up by key.
d[key] = valueadds a pair or replaces an existing value.d[key]raisesKeyErrorfor a missing key;d.get(key, default)returns a default instead.items()gives you key and value together in a loop.counts[item] = counts.get(item, 0) + 1is the standard way to count things.- Keys must be immutable, such as strings or numbers; lists cannot be keys.