Dictionaries
Learn how to store data as key-value pairs using dictionaries, one of the most useful data structures in Python.
Key and value pairs
A list stores items in order and you reach them by position number. A dictionary stores items as pairs: a key and a value. You reach a value using its key, not a position number. This is much more readable for many real situations.
Think of a real dictionary. You look up a word (the key) and find its definition (the value). Python dictionaries work exactly the same way.
person = {
"name": "Alice",
"age": 25,
"city": "London"
}
A dictionary is written with curly braces. Each pair is key: value, and pairs are separated by commas. Here "name" is a key and "Alice" is its value. Keys are usually strings or numbers and must be unique. Values can be anything, even lists or other dictionaries.
Use a list when the order or position matters, like a ranking. Use a dictionary when each piece of data has a label, like the fields on a form.
Reading values safely
person = {"name": "Alice", "age": 25, "city": "London"}
print(person["name"]) # Alice
print(person["age"]) # 25
Put the key in square brackets, and Python gives you the value. If you try to access a key that does not exist, Python raises a KeyError:
print(person["email"]) # KeyError: 'email'
The safer way is get(), which returns None (or a default you choose) if the key is not found:
print(person.get("email")) # None, no error
print(person.get("email", "N/A")) # N/A, custom default
Use square brackets when the key must be there, because an error then points out a real problem. Use get() when the key might be missing and that is fine.
Adding, updating and removing
Assigning to a key does two jobs. If the key is new, it adds a pair. If the key exists, it replaces the value. There is never a duplicate key:
person = {"name": "Alice", "age": 25}
person["email"] = "alice@example.com" # add a new key
person["age"] = 26 # update an existing key
print(person)
# {'name': 'Alice', 'age': 26, 'email': 'alice@example.com'}
To remove an entry, use del with the key, or pop(), which also gives the removed value back:
person = {"name": "Alice", "age": 25, "city": "London"}
del person["city"] # remove by key
print(person) # {'name': 'Alice', 'age': 25}
age = person.pop("age") # remove and return the value
print(age) # 25
print(person) # {'name': 'Alice'}
You can also merge another dictionary in with update():
person.update({"city": "Paris", "job": "Engineer"})
print(person) # {'name': 'Alice', 'city': 'Paris', 'job': 'Engineer'}
Looping through a dictionary
person = {"name": "Alice", "age": 25, "city": "London"}
# Loop through keys
for key in person:
print(key)
# Loop through key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
Output of the second loop:
name: Alice
age: 25
city: London
A plain for over a dictionary gives you the keys. Call .items() to get each key and value together, .values() for just the values, and .keys() for just the keys. Dictionaries remember the order in which you added the pairs, so the loop shows them in that same order.
Handy methods and nesting
person = {"name": "Alice", "age": 25, "city": "London"}
print(person.keys()) # dict_keys(['name', 'age', 'city'])
print(person.values()) # dict_values(['Alice', 25, 'London'])
print(len(person)) # 3
print("age" in person) # True, checks if the key exists
Note that in checks the keys, not the values. To test a value, use "Alice" in person.values().
A dictionary can hold another dictionary as a value. This lets you represent more complex, structured data:
users = {
"alice": {"age": 25, "email": "alice@example.com"},
"bob": {"age": 30, "email": "bob@example.com"}
}
print(users["alice"]["email"]) # alice@example.com
print(users["bob"]["age"]) # 30
Read it from left to right: first get the "alice" dictionary, then get its "email". You can also put dictionaries inside a list, which is how data from websites and databases usually looks:
students = [
{"name": "Ann", "grade": 90},
{"name": "Ben", "grade": 72},
]
for s in students:
print(s["name"], s["grade"])
A practical example: counting words
Dictionaries are great for counting things. Here is a program that counts how many times each word appears in a sentence:
sentence = "the cat sat on the mat and the cat slept"
words = sentence.split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
for word, count in word_count.items():
print(f"{word}: {count}")
the: 3
cat: 2
sat: 1
on: 1
mat: 1
and: 1
slept: 1
Walk through it. We start with an empty dictionary. For each word, if we have already seen it we add 1 to its count. If not, we add it with a count of 1. The same job is shorter with get():
for word in words:
word_count[word] = word_count.get(word, 0) + 1
get(word, 0) returns the old count, or 0 if the word is new, and then we add 1 and store it back.
Choosing the right tool
You now know two ways to store a group of data. Here is how to choose:
- List: an ordered collection where position matters, or where you just have many similar items. Examples: a playlist, a list of scores, steps in a recipe.
- Dictionary: a lookup table where each item has a name. Examples: a phone book, settings for a program, one student's record.
# A list needs you to remember what each position means
person = ["Alice", 25, "London"]
print(person[1]) # what is index 1?
# A dictionary says it out loud
person = {"name": "Alice", "age": 25, "city": "London"}
print(person["age"]) # clear
Dictionary lookups are also very fast, even with millions of entries. Python finds a key almost instantly instead of checking every item, which is why dictionaries are used everywhere in real programs. Keys must be of a type that cannot change, such as strings, numbers or tuples. You cannot use a list as a key.
Common mistakes
- KeyError. Reading a missing key with square brackets. Use
get()or checkinfirst. - Mixing up keys and values.
person["Alice"]is wrong. The key is"name". - Duplicate keys. Writing the same key twice keeps only the last value.
- Using
[]to add to a dictionary.{}is a dictionary, and[]is a list. An empty dictionary is{}. - Expecting
into check values. It checks keys.
d = {"a": 1, "a": 2}
print(d) # {'a': 2}
A good trick when a dictionary looks wrong is print(d). Python shows the whole thing in one line, so you can see which keys really exist.
Key takeaways
- A dictionary stores key and value pairs inside curly braces
- Read with
d[key]or the safed.get(key, default) - Assign
d[key] = valueto add or update. Usedelorpopto remove for key in dloops over keys, and.items()gives keys and values togetherinchecks keys.len()counts pairs- Dictionaries can nest, and a list of dictionaries is a common way to store records
- Use a list for ordered items and a dictionary for labeled data