Python Dictionaries Explained With Simple Examples
A Python dictionary stores key-value pairs, so you can look up a price by product name or a setting by its name rather than by position. Every example below was run in Python 3.13, and the output shown is what it printed.
On this page▾
| Operation | Result |
|---|---|
d[key] |
Value, or KeyError if missing |
d.get(key) |
Value, or None if missing |
d.get(key, default) |
Value, or the supplied default |
key in d |
Whether the key exists |
d.items() |
Key-value pairs for iteration |
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.
How for and while loops work is covered in Python Loops, For vs While, With Examples You Can Run.
A practical pattern: counting things
A dictionary can store a count for each distinct item. 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. Dictionary keys must be hashable, not merely immutable. Strings and numbers work; a tuple works only if all its elements are hashable. A tuple containing a list cannot be a key. Lists themselves cannot be keys. 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.
Sources
About this guide
Howlane operator · Checked against the official sources listed above. It is general information, not professional advice.
AboutEditorial standardsCorrectionsReport an error
Edit history
- Updated
- Updated
- Updated
- Updated
- Published