A dictionary (dict) maps keys to values. Instead of asking for "item number 3", you ask for "the price of bread". Lookups are fast no matter how big the dictionary gets, which is why dictionaries are everywhere in Python: configuration, JSON data, counting, caching.
Creating a dictionary
Write key–value pairs inside curly braces, with a colon between each key and its value:
prices = {"apple": 0.5, "bread": 1.2, "milk": 0.9}
print(prices)
print(len(prices))
{'apple': 0.5, 'bread': 1.2, 'milk': 0.9}
3
You can also build one with dict(), or start empty and fill it in:
person = dict(name="Asha", age=29)
scores = {}
scores["maths"] = 88
print(person, scores)
{'name': 'Asha', 'age': 29} {'maths': 88}
Keys must be unique and immutable: strings, numbers and tuples work; lists don't. Values can be anything, including lists or other dictionaries. Since Python 3.7, dictionaries remember the order in which keys were inserted.
Reading values
Use square brackets with the key:
prices = {"apple": 0.5, "bread": 1.2}
print(prices["bread"])
1.2
Asking for a key that doesn't exist raises a KeyError. When a key might be missing, use .get(), which returns None (or a default you choose) instead of crashing:
prices = {"apple": 0.5, "bread": 1.2}
print(prices.get("cheese"))
print(prices.get("cheese", 0))
print("apple" in prices)
None
0
True
The in operator checks keys, not values.
Adding, updating and removing
Assigning to a key adds it if it's new and replaces the value if it exists:
stock = {"apple": 10}
stock["bread"] = 4 # add
stock["apple"] = 7 # update
stock.update({"milk": 2, "bread": 6})
print(stock)
removed = stock.pop("milk")
del stock["apple"]
print(stock, removed)
{'apple': 7, 'bread': 6, 'milk': 2}
{'bread': 6} 2
.update() merges another dictionary in, overwriting matching keys. In Python 3.9 and later, a | b creates a new merged dictionary too.
Looping over a dictionary
Looping over a dictionary gives you its keys. Use .items() to get each key and value together, which is what you want most of the time:
scores = {"Asha": 82, "Ben": 74, "Chen": 91}
for name, score in scores.items():
print(f"{name} scored {score}")
print(list(scores.keys()))
print(sum(scores.values()))
Asha scored 82
Ben scored 74
Chen scored 91
['Asha', 'Ben', 'Chen']
247
To process items sorted by value, sort the pairs:
scores = {"Asha": 82, "Ben": 74, "Chen": 91}
best = sorted(scores.items(), key=lambda pair: pair[1], reverse=True)
print(best[0])
('Chen', 91)
Counting with a dictionary
Counting things is a classic dictionary job. .get(key, 0) makes it a one-liner:
counts = {}
for word in "to be or not to be".split():
counts[word] = counts.get(word, 0) + 1
print(counts)
{'to': 2, 'be': 2, 'or': 1, 'not': 1}
The standard library's collections.Counter does the same in one call, and collections.defaultdict creates missing keys automatically.
Nested dictionaries
Values can themselves be dictionaries, which is exactly the shape of JSON data from an API:
users = {
"u1": {"name": "Asha", "skills": ["python", "sql"]},
"u2": {"name": "Ben", "skills": ["excel"]},
}
print(users["u1"]["skills"][0])
for uid, info in users.items():
print(uid, info["name"], len(info["skills"]))
python
u1 Asha 2
u2 Ben 1
Dictionary comprehensions
Build a dictionary from a loop in one expression:
squares = {n: n * n for n in range(1, 5)}
print(squares)
prices = {"apple": 0.5, "bread": 1.2, "milk": 0.9}
cheap = {item: p for item, p in prices.items() if p < 1}
print(cheap)
{1: 1, 2: 4, 3: 9, 4: 16}
{'apple': 0.5, 'milk': 0.9}
setdefault, defaultdict and Counter
Three tools save you from writing "if the key is missing, create it" by hand.
setdefault(key, default) returns the value for key, inserting default first if the key is missing. It's useful for grouping:
groups = {}
for name, team in [("Asha", "red"), ("Ben", "blue"), ("Chen", "red")]:
groups.setdefault(team, []).append(name)
print(groups)
{'red': ['Asha', 'Chen'], 'blue': ['Ben']}
collections.defaultdict does the same automatically for every missing key, and collections.Counter is a dictionary built for counting:
from collections import defaultdict, Counter
groups = defaultdict(list)
for name, team in [("Asha", "red"), ("Ben", "blue"), ("Chen", "red")]:
groups[team].append(name)
print(dict(groups))
print(Counter("abracadabra").most_common(2))
{'red': ['Asha', 'Chen'], 'blue': ['Ben']}
[('a', 5), ('b', 2)]
Dictionary or list?
Use a list when order and position matter and you mostly go through the items one by one: a sequence of readings, a queue of tasks. Use a dictionary when you look things up by a meaningful key: a user by ID, a price by product, a setting by name.
The speed difference is real. Checking x in a_list scans the list item by item, so it gets slower as the list grows. Checking key in a_dict takes roughly the same tiny time whether the dictionary has ten keys or ten million, because dictionaries are built on a hash table. If you find yourself searching a list over and over, building a dictionary (or a set) once is usually the fix.
Common mistakes
KeyErrorfrom reading a missing key. Use.get()or check withinfirst.- Using a list as a key, which raises
TypeError: unhashable type: 'list'. Convert it to a tuple. - Changing a dictionary's size while looping over it, which raises
RuntimeError. Loop overlist(d)or build a new dictionary. - Expecting
into search values."Asha" in scoreschecks keys; usex in scores.values()for values. - Copy surprises.
b = adoesn't copy; usea.copy(). For nested dictionaries,copy.deepcopy(a).
Practice
- Given
stock = {"apple": 3, "pear": 0, "plum": 5}, print only the fruits that are in stock. - Invert
{"a": 1, "b": 2}so the values become keys. - Count how many times each character appears in
"banana"withoutCounter.
Answers
stock = {"apple": 3, "pear": 0, "plum": 5}
print([fruit for fruit, n in stock.items() if n > 0])
d = {"a": 1, "b": 2}
print({v: k for k, v in d.items()})
counts = {}
for ch in "banana":
counts[ch] = counts.get(ch, 0) + 1
print(counts)
['apple', 'plum']
{1: 'a', 2: 'b'}
{'b': 1, 'a': 3, 'n': 2}
Where this shows up in machine learning
Dictionaries hold hyperparameters ({"max_depth": 5, "n_estimators": 200}), and scikit-learn's GridSearchCV takes a dictionary mapping each parameter to the values to try. Model metrics often come back as dictionaries, JSON configs load as dictionaries, and a pandas DataFrame can be built straight from a dictionary of columns: pd.DataFrame({"age": [...], "income": [...]}). Label encoding, mapping category names to numbers, is a dictionary too.