A Python dictionary stores values under names — called keys — so you can look things up by what they are rather than where they are. A phone book is the classic example: you look up a person's name and get their number. This guide explains Python dictionaries simply, with examples you can run.
Creating a dictionary
Use curly braces, with each entry written as key: value:
ages = {"Sam": 34, "Ana": 29, "Leo": 41}
book = {"title": "Dune", "author": "Frank Herbert", "year": 1965}
empty = {}
Keys are usually strings, and each key appears only once. Values can be anything: numbers, text, lists, even other dictionaries.
Looking values up
ages = {"Sam": 34, "Ana": 29}
print(ages["Sam"]) # 34
Asking for a key that is not there crashes with a KeyError:
print(ages["Zoe"]) # KeyError: 'Zoe'
Two safe alternatives:
print(ages.get("Zoe")) # None
print(ages.get("Zoe", 0)) # 0 — a default of your choice
if "Zoe" in ages:
print(ages["Zoe"])
else:
print("No age for Zoe")
Adding, changing and removing entries
ages = {"Sam": 34}
ages["Ana"] = 29 # add a new key
ages["Sam"] = 35 # change an existing one
del ages["Ana"] # remove a key
print(ages) # {'Sam': 35}
Note that adding and changing use exactly the same syntax. If the key exists, its value is replaced; if not, it is added.
Looping over a dictionary
prices = {"apple": 0.5, "bread": 2.2, "milk": 1.1}
for item in prices: # keys
print(item)
for item, price in prices.items(): # keys and values together
print(f"{item}: {price:.2f}")
.items() is the one you will use most. .keys() and .values() give you just one side.
Counting with a dictionary
One of the most useful patterns in beginner Python: counting how often things appear.
words = ["cat", "dog", "cat", "bird", "cat"]
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts) # {'cat': 3, 'dog': 1, 'bird': 1}
The first time a word is seen, get returns 0; after that, it returns the running count. The same pattern counts letters, votes, errors in a log, anything.
The dictionary tools you will use most
| Code | What it does |
|---|---|
d[key] | Get a value (crashes if missing) |
d.get(key, default) | Get a value, or the default if missing |
d[key] = value | Add or change an entry |
del d[key] | Remove an entry |
key in d | True if the key exists |
len(d) | Number of entries |
d.items() | Key–value pairs, for looping |
d.keys(), d.values() | Just the keys, or just the values |
Nesting: dictionaries inside dictionaries
Real data often has several fields per item. A dictionary of dictionaries handles it neatly:
contacts = {
"Sam": {"phone": "555-0101", "email": "sam@example.com"},
"Ana": {"phone": "555-0102", "email": "ana@example.com"},
}
print(contacts["Ana"]["email"]) # ana@example.com
And a list of dictionaries is the usual shape for rows of data, such as a spreadsheet:
orders = [
{"item": "lamp", "qty": 2},
{"item": "desk", "qty": 1},
]
for order in orders:
print(order["item"], order["qty"])
This is exactly the shape of JSON, the format most websites and services use to exchange data — so learning dictionaries well pays off later.
List or dictionary?
- Use a list when order matters and you think in terms of "first", "next", "last".
- Use a dictionary when you look things up by name: a person's details, a product's price, settings.
A useful warning sign: if you write person[2] and have to remember that position 2 is the phone number, you want person["phone"] instead. Our guide to Python lists explained for beginners covers the other side.
Practise
- Create a dictionary of three friends and their birthdays; print one by name.
- Count the letters in a sentence using the counting pattern above.
- Build a contact book that lets the user add and look up numbers — project eight in our Python projects for complete beginners.
If you hit a KeyError along the way, Python errors beginners make explains it and its cousins. Wrapping these patterns in reusable code is the subject of Python functions explained.
Dictionaries — keys, values and nesting — have their own lesson in the data structures part of Python for Beginners, followed by a lesson on JSON basics that builds directly on them. The free Practice Toolkit on the Python for Beginners page has graded dictionary exercises with answers.
Frequently asked questions
Are Python dictionaries ordered?
Yes. Since Python 3.7, dictionaries keep the order in which keys were added.
Can two keys be the same?
No. Assigning to an existing key replaces its value.
What can be a dictionary key?
Any value that cannot change, such as a string, a number or a tuple. Lists cannot be keys.