A list finds things by position: "give me item number 2". A dictionary finds things by name: "give me the age". It stores key-value pairs, so each piece of data has a label.
Creating dictionaries
Use curly braces, with key: value pairs separated by commas:
person = {
"name": "Ada",
"age": 36,
"language": "Python",
}
empty = {}
print(len(person)) # 3Keys are usually strings or numbers, and each key can appear only once. Values can be anything, including lists and other dictionaries.
Accessing and modifying values
Look up a value by putting its key in square brackets:
print(person["name"]) # AdaWarning
Asking for a key that doesn't exist raises a KeyError. Use .get() when the key might be missing.
print(person.get("email")) # None
print(person.get("email", "unknown")) # unknown.get(key, default) returns the default instead of crashing.
Assigning to a key either updates an existing entry or adds a new one:
person["age"] = 37 # update
person["email"] = "ada@mail.com" # add
del person["language"] # delete
print(person)
# {'name': 'Ada', 'age': 37, 'email': 'ada@mail.com'}Check whether a key exists with in:
print("name" in person) # True
print("phone" in person) # FalseDictionary methods
| Method | What it does |
|---|---|
.get(k) / .get(k, default) | safe lookup |
.keys() | all the keys |
.values() | all the values |
.items() | all the (key, value) pairs |
.pop(k) | remove a key and return its value |
.update(other) | merge in another dictionary |
.clear() | remove everything |
stock = {"apple": 5, "pear": 2}
print(list(stock.keys())) # ['apple', 'pear']
print(list(stock.values())) # [5, 2]Iterating over dictionaries
A plain for loop goes through the keys. Use .items() to get the key and value together, unpacked like a tuple:
stock = {"apple": 5, "pear": 2, "fig": 12}
for item in stock:
print(item)
for item, qty in stock.items():
print(f"{item}: {qty}")Output of the second loop:
apple: 5
pear: 2
fig: 12
Dictionaries remember the order in which keys were added. If you want them in a different order, loop over sorted(stock) to go through the keys alphabetically or numerically.
A very common pattern: counting
counts = {}
for letter in "banana":
counts[letter] = counts.get(letter, 0) + 1
print(counts) # {'b': 1, 'a': 3, 'n': 2}counts.get(letter, 0) returns 0 the first time a letter shows up, so you never need to check whether the key exists first.
Tip
Whenever you catch yourself wanting to "count how many of each thing", reach for a dictionary.
Nested dictionaries
Values can be dictionaries (or lists) too, which lets you model richer data:
students = {
"ada": {"age": 36, "grades": [90, 85]},
"alan": {"age": 41, "grades": [70, 95, 88]},
}
print(students["ada"]["age"]) # 36
print(students["alan"]["grades"][1]) # 95
students["ada"]["grades"].append(100)Read it from left to right: first get the "ada" dictionary, then get the "age" inside it.
Lists as values are great for grouping. Here we collect words under the first letter of each word:
groups = {}
for word in ["apple", "avocado", "banana"]:
letter = word[0]
if letter not in groups:
groups[letter] = []
groups[letter].append(word)
print(groups) # {'a': ['apple', 'avocado'], 'b': ['banana']}Which things can be used as keys?
Keys have to be immutable: strings, numbers, booleans, and tuples all work. Lists, sets, and other dictionaries don't, because they can change after being used as a key.
Now try it yourself. The next step is three puzzles using dictionaries to count, look up, and group data.