Python Dictionaries: Store and Retrieve Key-Value Pairs
Understand how to use Python dictionaries to store labeled data as key-value pairs. Learn the syntax for creating dictionaries, adding and updating items, and looping through keys and values. This lesson enables you to organize data effectively and retrieve it quickly within your programs.
We'll cover the following...
So far, you’ve used variables to store single pieces of data and lists to store collections. But what if you want to label your data with keywords? That’s where dictionaries come in—Python’s way of storing key–value pairs!
A dictionary in Python
Think of a dictionary like a real one:
We look up a word (the key).
We get a definition (the value).
Let’s look at the syntax first:
person = {"name": "Ava", # Key is "name", value is "Ava""age": 25, # Key is "age", value is 25 (notice: no quotes around numbers)"city": "Seattle" # Strings must be in quotes, and each key-value pair ends with a comma}
The whole dictionary is wrapped in {}, and each key and value is joined with a :. We can get a value by asking for its key:
print(person["name"])
Let’s run it:
We just used a dictionary to store and access information.
Add and update items
We can add a new item or update an existing one like this:
Now Python remembers a bunch of labeled data.
Loop through a dictionary
We can loop through both keys and values using a for loop:
What’s happening here?
person.items()gives us all the key–value pairs in the dictionary.for key, value in ...splits each pair so you can work with them separately.Inside the loop, you can print or use the key and value however you like.
This is a powerful way to display all your data, especially when you don’t know the keys in advance.