After this lesson you can store information under meaningful names instead of positions, and look it up, change it and remove it. A dictionary (written dict in Python) is the natural way to hold a record such as one student or one product.
Keys and values
A list finds things by position. A dictionary finds things by a key that you choose. Each key is paired with a value:
student = {"name": "Asha", "age": 21, "course": "Python"}
print(student)
print(student["name"])
print(student["age"])
print(len(student))
print(type(student)){'name': 'Asha', 'age': 21, 'course': 'Python'}
Asha
21
3
<class 'dict'>Read the line student["name"] as "the value stored under the key name". The keys here are strings, but they can be any hashable value, such as numbers or tuples. Values can be anything at all, including lists and other dictionaries.
An empty dictionary is {}. You can also build one with dict():
empty = {}
point = dict(x=3, y=7)
pairs = dict([("a", 1), ("b", 2)])
print(empty)
print(point)
print(pairs){}
{'x': 3, 'y': 7}
{'a': 1, 'b': 2}Adding and changing entries
Assigning to a key does one of two things. If the key is new it adds an entry. If the key exists it replaces the value.
student["city"] = "Pune"
student["age"] = 22
print(student){'name': 'Asha', 'age': 22, 'course': 'Python', 'city': 'Pune'}Keys are unique. If you write the same key twice in one dictionary, the last value wins:
prices = {"tea": 20, "coffee": 30, "tea": 25}
print(prices){'tea': 25, 'coffee': 30}Since Python 3.7 a dictionary also remembers the order in which keys were first added, and printing or looping gives them back in that order. This is part of the language, so you can rely on it. Older versions made no such promise.
Reading safely
Reading a key that is not there raises a KeyError:
student["email"]KeyError: 'email'When a missing key is normal and not a bug, use get. It returns None by default, or the second argument if you give one:
print(student.get("email"))
print(student.get("email", "not given"))
print(student.get("name", "not given"))None
not given
AshaYou can also test first with in. For dictionaries in looks at the keys:
print("name" in student)
print("Asha" in student)
print("Asha" in student.values())True
False
TrueThe second line is False because "Asha" is a value, not a key. Asking student.values() is how you search values.
Removing entries
Use del for a known key, or pop to remove it and get the value back. pop also accepts a default so that a missing key is not an error:
del student["city"]
print(student)
removed = student.pop("course")
print(removed)
print(student.pop("course", "already gone"))
print(student){'name': 'Asha', 'age': 22, 'course': 'Python'}
Python
already gone
{'name': 'Asha', 'age': 22}Counting with a dictionary
A classic use is counting how often things occur. Keep each item as a key and its count as the value:
basket = ["pen", "book", "pen", "ruler", "pen", "book"]
counts = {}
for item in basket:
counts[item] = counts.get(item, 0) + 1
print(counts){'pen': 3, 'book': 2, 'ruler': 1}For every item, counts.get(item, 0) gives the count so far, or 0 for a new item, and we store it back plus one. Reading counts[item] directly would raise a KeyError on the first sight of each item, which is exactly why get with a default is so handy here.
What can be a key
Keys must be hashable, in practice immutable: strings, numbers, tuples of those, and so on. A list is not allowed, because it could change after being stored.
bad = {[1, 2]: "list key"}TypeError: unhashable type: 'list'Tuples work, which is useful for things like grid positions:
board = {(0, 0): "X", (1, 1): "O"}
print(board[(1, 1)])OCommon mistakes
- Reading a missing key with square brackets. It raises
KeyError. Usegetor check withinwhen the key may not exist. - Checking
infor a value.intests keys. Use.values()to test values. - Repeating a key and expecting both entries. The later value silently replaces the earlier one.
- Using a list as a key. Use a tuple, or rethink the structure.
- Confusing
{}with an empty set.{}is an empty dictionary; useset()for a set.
Exercise
Create a dictionary book with the keys "title", "author" and "pages" for any fictional book. Add a key "available" set to True, change "pages" to a new number, and print the title using get with a default of "unknown". Then print what get returns for a key "isbn" that does not exist.
Show one possible answer
book = {"title": "Learning Maps", "author": "R. Example", "pages": 180}
book["available"] = True
book["pages"] = 200
print(book.get("title", "unknown"))
print(book.get("isbn"))
print(book)Learning Maps
None
{'title': 'Learning Maps', 'author': 'R. Example', 'pages': 200, 'available': True}Previous: Sets. Next: Dictionary methods and loops.
Key points
- A dictionary maps keys to values and is written with curly braces: {"name": "Asha", "age": 21}.
- Read a value with d[key]. A missing key raises KeyError, while d.get(key) returns None or a default you supply.
- Assigning to a key adds it if new or replaces the value if it exists. Keys must be unique and hashable.
- From Python 3.7 a dictionary remembers the order in which keys were inserted. The in operator checks keys, not values.