Thanks to visit codestin.com
Credit goes to www.pythonmorsels.com

Using dictionaries in Python

Share
Copied to clipboard.
Trey Hunner smiling in a t-shirt against a yellow wall
Trey Hunner
2 min. read Watch as video Python 3.10—3.14

Let's talk about dictionaries in Python.

What are dictionaries for?

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.

Looking up the value for a 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'

Updating the value for a key

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'}

Adding new key-value pairs

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'

Checking whether a dictionary has a certain key

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

Dictionaries verses lists

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'

Use dictionaries when you need a lookup table

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.

🚀
New to Python? Try Python Jumpstart!

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.

5 Keys to Python Success 🔑

Sign up for my 5 day email course and learn essential concepts that introductory courses often overlook!