Dictionaries
Overview
Lists find things by position. But often you want to find things by name: the price of “tea”, the phone number for “Asha”, the capital of “France”. A dictionary (dict) stores key → value pairs and finds any value by its key instantly, however big the dictionary gets.
Creating a dictionary
prices = {"tea": 3.5, "coffee": 4.0, "cake": 5.25}
ages = {"Asha": 29, "Ben": 34}
empty = {}Each entry is key: value, separated by commas, inside curly braces.
- Keys are unique. Assigning to an existing key replaces its value.
- Keys must be immutable: strings, numbers or tuples. Lists can’t be keys.
- Values can be anything: numbers, strings, lists, other dictionaries.
- Dictionaries remember insertion order: loops go through keys in the order they were added.
Reading values
prices["tea"] # 3.5
prices["pie"] # KeyError: 'pie'
prices.get("pie") # None — no error
prices.get("pie", 0) # 0 — your default
"tea" in prices # True — checks KEYS, not values
len(prices) # 3Use d[key] when the key must exist (a missing key is a bug you want to hear about); use d.get(key, default) when missing is normal.
Adding, changing and removing
prices["pie"] = 4.75 # add a new key
prices["tea"] = 3.75 # change an existing one
prices["tea"] += 0.25 # update based on the old value
del prices["cake"] # remove (KeyError if absent)
price = prices.pop("pie") # remove AND return the value
prices.pop("muffin", None) # no error if absent
prices.update({"tea": 4.0, "scone": 3.0}) # add/overwrite several
prices |= {"juice": 2.5} # the same, with an operatorLooping over a dictionary
for item in prices: # keys
print(item)
for price in prices.values(): # values
print(price)
for item, price in prices.items(): # both — the most common
print(f"{item}: {price:.2f}")items() gives (key, value) tuples, which the loop unpacks. To loop in sorted order, wrap it: for item, price in sorted(prices.items()): sorts by key.
As with lists, don’t add or remove keys while looping over the dictionary itself (Python raises RuntimeError: dictionary changed size during iteration). Loop over list(d) instead if you must.
Counting with a dictionary
One of the most useful patterns in programming — count how many times each thing appears:
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1get(word, 0) returns the current count, or 0 the first time a word is seen. (The standard library’s collections.Counter does this in one line — see The standard library.)
To find the key with the largest value: max(counts, key=counts.get).
Grouping with a dictionary of lists
groups = {}
for name, team in [("Asha", "red"), ("Ben", "blue"), ("Chen", "red")]:
groups.setdefault(team, []).append(name)
# {'red': ['Asha', 'Chen'], 'blue': ['Ben']}setdefault(key, default) returns the existing value, or inserts the default first if the key is missing.
Nested data
Dictionaries and lists combine to describe almost any data — this is exactly the shape of JSON from web APIs (CSV and JSON):
user = {
"name": "Asha",
"languages": ["Python", "SQL"],
"address": {"city": "Pune", "country": "IN"},
}
user["languages"][0] # 'Python'
user["address"]["city"] # 'Pune'Building dictionaries
dict(tea=3.5, coffee=4.0) # keyword style
dict(zip(["a", "b"], [1, 2])) # {'a': 1, 'b': 2}
{name: len(name) for name in ["Asha", "Ben"]} # dict comprehension (next lessons)When to use a dictionary: whenever you think “look up X by Y” — prices by item, users by ID, counts by word.
Word counter and inventory
(1) Count how often each word appears in the sentence in the starter (ignore case and the full stop) using a dictionary and .get(), then print the counts for the and cat, and the most common word with its count. (2) For the inventory: add "pears": 8, reduce apples by 2, remove bananas with .pop() and print how many were removed, then print each item as apples: 10 in alphabetical order of the item names.
sentence = "The cat sat on the mat and the dog sat on the cat."
# 1. Word counts
counts = {}
inventory = {"apples": 12, "bananas": 5, "cherries": 30}
# 2. Update and print the inventorysentence = "The cat sat on the mat and the dog sat on the cat."
# 1. Word counts
counts = {}
for word in sentence.lower().replace(".", "").split():
counts[word] = counts.get(word, 0) + 1
print("the:", counts["the"], "cat:", counts["cat"]) # the: 4 cat: 2
best = max(counts, key=counts.get)
print("Most common:", best, counts[best]) # Most common: the 4
inventory = {"apples": 12, "bananas": 5, "cherries": 30}
# 2. Update and print the inventory
inventory["pears"] = 8
inventory["apples"] -= 2
removed = inventory.pop("bananas")
print("Removed bananas:", removed) # 5
for item, quantity in sorted(inventory.items()):
print(f"{item}: {quantity}")Summary
- A dictionary maps unique keys to values:
{"tea": 3.5}; look up withd[key]. d[key] = valueadds or updates;del d[key]ord.pop(key)removes.d[key]raises KeyError if the key is missing;d.get(key, default)returns a default instead.- Loop with
for key, value in d.items():; dictionaries keep insertion order. - Keys must be immutable (strings, numbers, tuples); values can be anything, including lists and other dicts.