Lesson 6 - Python Dictionaries
On this page
- Why Do We Need Dictionaries?
- What Is a Dictionary?
- Try It Yourself
- Accessing Values in a Dictionary
- Try It Yourself
- Building a Dictionary Step by Step
- Try It Yourself
- Understanding Key-Value Pairs
- Try It Yourself
- Why Some Keys Don’t Work
- When Keys Collide
- Special Case: Booleans as Keys
- Practice Time
- Summary: What You’ve Learned About Dictionaries
- Next Steps
In this lesson, we’re going to learn about a new type of data structure in Python: dictionaries.
By the end of this lesson, you’ll be able to:
- Understand what a dictionary is and why it’s useful
- Create dictionaries and access their values
- Understand key-value pairs
- Use dictionaries to store and retrieve information clearly and efficiently
Let’s jump in.
Why Do We Need Dictionaries?
So far, we’ve used lists to store groups of values. But sometimes, lists aren’t enough.
Here’s an example. Imagine we have this table of app content ratings from a dataset of mobile apps:
Content Rating | Number of Apps |
---|---|
4+ | 4433 |
9+ | 987 |
12+ | 1155 |
17+ | 622 |
We want to store this information in Python.
The first way to do it is using two separate lists:
content_ratings = ['4+', '9+', '12+', '17+']
numbers = [4433, 987, 1155, 622]
Or maybe a list of lists:
content_rating_numbers = [['4+', '9+', '12+', '17+'],
[4433, 987, 1155, 622]]
But here’s the problem: What if you want to know how many apps have a content rating of '12+'
?
You’d have to:
- Find the index of
'12+'
in the first list - Use that index to look up the number in the second list
That’s not very convenient, especially if you’re dealing with more data. Also, someone reading your code might not immediately understand what the lists mean.
We need a better way to map content ratings directly to the number of apps — and that’s where dictionaries come in.
What Is a Dictionary?
A dictionary in Python lets us store data as key-value pairs.
Here’s how we can store our content ratings and app counts using a dictionary:
content_ratings = {
'4+': 4433,
'9+': 987,
'12+': 1155,
'17+': 622
}
Now, if we want to know how many apps are rated '12+'
, we can do this:
print(content_ratings['12+']) # Output: 1155
No index searching, no confusion — we go straight from the key ('12+'
) to the value (1155
).
This is the main idea of dictionaries: each key points to a value.
Let’s break that down:
- The key is the thing we want to look up (like
'4+'
). - The value is the data we want to store (like
4433
). - The full structure is surrounded by curly braces
{}
. - Each key-value pair is separated by a colon
:
. - Multiple pairs are separated by commas.
Let’s write that again to reinforce it:
content_ratings = {
'4+': 4433,
'9+': 987,
'12+': 1155,
'17+': 622
}
When we print it out, we get:
{'4+': 4433, '9+': 987, '12+': 1155, '17+': 622}
That’s much clearer than juggling two separate lists.
Try It Yourself
Let’s practice writing a dictionary.
Instructions:
- Create a dictionary called
content_ratings
. - Use the following key-value pairs:
'4+'
: 4433'9+'
: 987'12+'
: 1155'17+'
: 622
- Print the dictionary.
Here’s the starting point:
# Your turn
content_ratings = {
'4+': 4433,
'9+': 987,
'12+': 1155,
'17+': 622
}
print(content_ratings)
Great! Now that we know how to create a dictionary, let’s learn how to access the values stored inside it.
Accessing Values in a Dictionary
When we use a list, we access values by their position — their index number. But with dictionaries, we use the key to look up its corresponding value.
Let’s take our content_ratings
dictionary again:
content_ratings = {
'4+': 4433,
'9+': 987,
'12+': 1155,
'17+': 622
}
If we want to find out how many apps are rated '9+'
, we don’t need to remember the index. We just use the key directly:
print(content_ratings['9+']) # Output: 987
You can do this with any of the keys:
print(content_ratings['4+']) # 4433
print(content_ratings['12+']) # 1155
print(content_ratings['17+']) # 622
Much easier than using index numbers!
Just remember — if you try to use a key that doesn’t exist, you’ll get an error:
print(content_ratings['18+']) # KeyError
So make sure the key is in the dictionary before you try to access it.
Try It Yourself
Let’s write some code to practice retrieving values.
Instructions:
- Use the existing
content_ratings
dictionary. - Create a variable named
over_9
and assign it the value of the'9+'
key. - Create a variable named
over_17
and assign it the value of the'17+'
key. - Print both variables.
Here’s a template to help you get started:
content_ratings = {
'4+': 4433,
'9+': 987,
'12+': 1155,
'17+': 622
}
over_9 = content_ratings['9+']
over_17 = content_ratings['17+']
print(over_9)
print(over_17)
Building a Dictionary Step by Step
So far, we’ve seen how to create a dictionary by writing out all the key-value pairs at once. That’s useful when we already know everything we want to include. But what if we want to build a dictionary gradually?
Python lets us do that too.
Step-by-step dictionary creation:
You can start with an empty dictionary and add items one by one like this:
content_ratings = {}
content_ratings['4+'] = 4433
content_ratings['9+'] = 987
content_ratings['12+'] = 1155
content_ratings['17+'] = 622
print(content_ratings)
Output:
{'4+': 4433, '9+': 987, '12+': 1155, '17+': 622}
This method is useful when:
- You’re generating key-value pairs in a loop.
- You’re receiving the data from an external file or user input.
- You just prefer building things piece by piece.
It works very similarly to appending values to a list. Instead of using append()
, you use square brackets to assign a value to a key.
Try It Yourself
Let’s practice this approach.
Instructions:
- Create an empty dictionary called
content_ratings
. - Add the key-value pairs using the format
dictionary[key] = value
:'4+': 4433
'9+': 987
'12+': 1155
'17+': 622
- Then, retrieve the value for the
'12+'
key and assign it to a variable calledover_12_n_apps
. - Print
over_12_n_apps
.
Here’s a sample to help guide you:
content_ratings = {}
content_ratings['4+'] = 4433
content_ratings['9+'] = 987
content_ratings['12+'] = 1155
content_ratings['17+'] = 622
over_12_n_apps = content_ratings['12+']
print(over_12_n_apps)
This shows you how we can build up dictionaries programmatically, rather than hard-coding them in one go.
Understanding Key-Value Pairs
Now let’s talk more about how dictionaries work under the hood — and what makes them different from lists.
In a dictionary, each item is a key-value pair.
Think of it like a label on a box:
- The key is the label.
- The value is what’s inside the box.
Here’s an example:
content_ratings = {
'4+': 4433,
'9+': 987,
'12+': 1155,
'17+': 622
}
In '4+': 4433
,
'4+'
is the key4433
is the value Together, they form a key-value pair.
You can use any immutable data type as a key: ✅ Strings, numbers, floats, booleans — all fine. ❌ Lists and dictionaries — not allowed as keys.
Why? Because Python needs keys to stay the same (unchanged) over time. Lists and dictionaries can change — so Python doesn’t allow them as keys.
Let’s see a few examples:
d = {
4: 'integer',
'4': 'string',
4.0: 'float',
True: 'boolean'
}
print(d)
Output:
{4: 'float', '4': 'string', True: 'boolean'}
Notice something strange? 4
and 4.0
are considered the same key because Python uses a system called hashing
behind the scenes, and it treats them as equal.
Let’s see what happens when we try using a list as a key:
invalid_dict = {
[1, 2, 3]: 'list'
}
Output:
TypeError: unhashable type: 'list'
Same with dictionaries:
invalid_dict = {
{'key': 'value'}: 'dictionary'
}
Output:
TypeError: unhashable type: 'dict'
So remember:
✅ You can use strings, integers, floats, booleans as keys ❌ You cannot use lists or dictionaries as keys
Try It Yourself
Here’s a small challenge for you.
Below is a dictionary definition. Your job is to decide if it’s valid or not. If it will raise an error, set the variable error
to True
. If not, set it to False
.
# Will this dictionary raise an error?
{
4: 'four',
1.5: 'one point five',
'string_key': 'string_value',
True: 'True',
[1,2,3]: 'a list',
{10: 'ten'}: 'a dictionary'
}
Hint: Using a list or a dictionary as a key is not allowed.
Your code:
error = True
print(error)
This exercise helps you think more deeply about what types can (and cannot) be used in dictionaries.
Why Some Keys Don’t Work
Let’s take a closer look at why lists and dictionaries can’t be used as keys.
Behind the scenes, Python uses something called the hash()
function when working with dictionaries. It takes a key and turns it into a number that helps Python quickly find and store values.
Let’s try it with keys that do work:
print(hash(4)) # Works fine
print(hash('four')) # Works fine
print(hash(3.32)) # Also fine
print(hash(True)) # Yep, this one too
You’ll get a bunch of numbers back, like:
4
-920017357099582350
737869762948381699
1
But when you try hash()
on a list:
print(hash([1, 2, 3]))
You’ll see this:
TypeError: unhashable type: 'list'
Same for dictionaries:
print(hash({'key': 'value'}))
That’s why these types can’t be used as dictionary keys — Python literally doesn’t know how to “hash” them.
When Keys Collide
Another thing you need to watch out for is duplicate keys.
Python dictionaries require all keys to be unique. If you use the same key more than once, Python keeps only the last value.
Here’s what happens:
d = {
'a_key': 1,
'another_key': 2,
'a_key': 3,
'yet_another_key': 4,
'a_key': 5
}
print(d)
Output:
{'a_key': 5, 'another_key': 2, 'yet_another_key': 4}
So even though 'a_key'
was assigned 3 different values, only the last one survives.
Special Case: Booleans as Keys
There’s one more Python quirk you should know about:
d1 = {1: 'one', True: 'boolean'}
d2 = {False: 'bool', 0: 'zero'}
You might expect this:
{1: 'one', True: 'boolean'}
But here’s what Python gives you:
{1: 'boolean'}
{False: 'zero'}
Why?
Because in Python:
True
is treated like the number1
False
is treated like0
So if you use both in the same dictionary, they conflict.
Here’s another example:
d3 = {
0: 'zero',
1: 'one',
2: 'two',
True: 'true',
False: 'false'
}
print(d3)
Output:
{0: 'false', 1: 'true', 2: 'two'}
False
overrides 0
, and True
overrides 1
. This kind of bug is easy to miss, so be careful when mixing booleans and numbers as dictionary keys!
Practice Time
Create the following dictionary and assign it to a variable called d_1
. Make sure all values are valid:
d_1 = {
'key_1': 'first_value',
'key_2': 2,
'key_3': 3.14,
'key_4': True,
'key_5': [4, 2, 1],
'key_6': {'inner_key': 6}
}
All keys are valid here (they’re all strings), and we’re using different types of values: string, integer, float, boolean, list, and even another dictionary.
This wraps up our detailed look at how dictionaries work and what to avoid when using them.
Summary: What You’ve Learned About Dictionaries
You’ve just learned a lot about Python dictionaries — nice work!
Let’s quickly summarize the key takeaways from this lesson so you can revisit them anytime.
✅ How to Create a Dictionary
There are two main ways to create a dictionary:
1. All at once (literal syntax):
content_ratings = {
'4+': 4433,
'9+': 987,
'12+': 1155,
'17+': 622
}
2. Step-by-step (using an empty dictionary):
content_ratings = {}
content_ratings['4+'] = 4433
content_ratings['9+'] = 987
content_ratings['12+'] = 1155
content_ratings['17+'] = 622
🔍 Accessing Dictionary Values
You can get values by using their keys:
apps_9_plus = content_ratings['9+']
apps_17_plus = content_ratings['17+']
You can also assign those values to variables and print them:
print(apps_9_plus) # 987
print(apps_17_plus) # 622
🧠 Key Concepts
- A dictionary stores data in key-value pairs.
- Keys must be unique.
- Keys must be hashable — you can use strings, numbers, or tuples (but not lists or other dictionaries).
- Dictionary values can be of any type, including lists and even other dictionaries.
- If you reuse the same key, Python keeps only the last value.
- Booleans (
True
,False
) are treated like1
and0
. Be careful mixing them with actual integers.
💡 Bonus Tips
- Use dictionaries when you want to quickly look up values by a label (like
'12+'
). - Dictionaries are faster than lists for lookups — that’s one reason they’re used a lot in real-world applications.
- You’ll often use dictionaries in data science to count, map, and group values.
Next Steps
In the next lesson, you’ll learn how to:
- Add and update values in dictionaries
- Delete key-value pairs
- Loop through keys, values, or both
- Use useful dictionary methods like
.get()
,.items()
,.keys()
, and.values()
All with practical examples using real datasets.
When you’re ready, let’s dive into those next-level dictionary skills. See you there!