Let's talk about dictionaries in Python.
mappingdefinition in Python Terminology.
Here's a dictionary:
>>> rooms = {"Pink": "Room 403", "Ocean": "Room 205", "Space": "Room 201"}
Dictionaries map keys to values.
In the above dictionary, we're mapping the names of each room to its room number.
Our keys (the room names) are Pink, Ocean, and Space.
Dictionaries are meant to make it easy to look up the value that corresponds to a particular key.
We can look up the value for a key by using square brackets ([]).
Here we're looking up the value for the key Pink (the value is Room 403):
>>> rooms["Pink"]
'Room 403'
If we wanted to update the value for a key, we can use square brackets along with an equal sign to assign a new value to that key.
>>> rooms["Pink"] = "Room 307"
We've just assigned the value for the key Pink to Room 307.
>>> rooms
{'Pink': 'Room 307', 'Ocean': 'Room 205', 'Space': 'Room 201'}
What if we wanted to add a new key-value pair to our dictionary?
You might guess that dictionaries have an add method or maybe an append method.
But they don't:
>>> rooms.add("Duck", "Room 10")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'add'
>>> rooms.append("Duck", "Room 10")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'append'
The syntax for adding a new key-value pair to a dictionary is actually the same as the syntax for updating the value for an existing key. We use square brackets along with the equal sign.
Here we're adding a new key to our dictionary.
>>> rooms["Duck"] = "Room 10"
We just added the key Duck with a value of Room 10:
>>> rooms["Duck"]
'Room 10'
If we wanted to check whether our dictionary has a particular key within it, we can use Python's in operator:
>>> "Space" in rooms
True
The in operator on dictionaries only checks for the presence of a key.
If we give it something that represents a value but not a key, we'll get back False:
>>> "Room 307" in rooms
False
What would you use a dictionary for in Python? Why not just use a list instead?
>>> rooms = [("Pink", 403), ("Ocean", 205), ("Space", 201), ("Duck", 10)]
Lists in Python are typically used for storing items in a particular order. It's common to append new items to the end of a list:
>>> rooms.append(("Unicorn", 326))
And we usually retrieve data from lists by looping over them.
>>> for name, number in rooms:
... print(f"Room {number}: {name}")
...
Room 403: Pink
Room 205: Ocean
Room 201: Space
Room 10: Duck
Room 326: Unicorn
Dictionaries, on the other hand, are usually used as a lookup table.
>>> rooms = {"Pink": "Room 403", "Ocean": "Room 205", "Space": "Room 201"}
The most common action you'll see performed on a dictionary is to look up the value for a particular key.
>>> rooms["Ocean"]
'Room 205'
When you need to look up one value based on another in Python, you can use a dictionary as a mapping of key-value pairs.
Python Jumpstart is designed to help new Python programmers get up to speed quickly. Get hands-on practice with 50 bite-sized modules that build your Python skills step by step.
Sign up for my 5 day email course and learn essential concepts that introductory courses often overlook!
Sign in to your Python Morsels account to track your progress.
Don't have an account yet? Sign up here.
Sign up for my free 5 day email course and learn essential concepts that introductory courses often overlook: iterables, callables, pointers, duck typing, and namespaces. Learn to avoid beginner pitfalls, in less than a week!
Ready to level up? Sign up now to begin your Python journey the right way!