Dictionaries
A dictionary (dict) stores key-value pairs, like {"name": "Asha", "age": 30}. You look values up by key (person["name"]), use .get() when a key might be missing, and loop over pairs with .items(). Dictionaries are how Python represents most real-world data, including JSON.
Creating and reading
person = {"name": "Asha", "city": "Pune", "age": 30}
print(person["name"])
print(len(person))
print("city" in person)Asha 3 True
Keys are usually strings, and each key appears only once. Values can be anything: numbers, lists, even other dictionaries.
Missing keys and .get()
person = {"name": "Asha"}
print(person.get("email"))
print(person.get("email", "not given"))
try:
print(person["email"])
except KeyError as err:
print("KeyError:", err)None not given KeyError: 'email'
Adding, changing and removing
stock = {"apples": 10}
stock["pears"] = 4 # add
stock["apples"] -= 3 # change
stock.update({"kiwis": 6, "pears": 5})
removed = stock.pop("kiwis")
print(stock)
print(removed){'apples': 7, 'pears': 5}
6Looping over a dictionary
prices = {"coffee": 3.2, "tea": 2.5, "cake": 4.0}
for item, price in prices.items():
print(f"{item:<8}{price:>6.2f}")
print(list(prices.keys()))
print(sum(prices.values()))coffee 3.20 tea 2.50 cake 4.00 ['coffee', 'tea', 'cake'] 9.7
Dictionaries remember the order you inserted keys in, so loops always run in that order.
Counting things
words = "the cat and the hat and the bat".split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
from collections import Counter
print(Counter(words).most_common(2)){'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
[('the', 3), ('and', 2)]Nested data, just like JSON
order = {
"id": 1042,
"customer": {"name": "Ben", "country": "BE"},
"items": [
{"product": "mug", "qty": 2},
{"product": "tea", "qty": 1},
],
}
print(order["customer"]["name"])
print(order["items"][0]["product"])
print(sum(i["qty"] for i in order["items"]))Ben mug 3
API responses and config files almost always look like this. Read them by chaining keys and positions from the outside in.
Practice
Count the votes in votes = ["python", "rust", "python", "go", "python", "go"] with a dictionary, then print each language and its count on its own line, like python: 3, in the order they first appear.
python: 3 rust: 1 go: 2