By the end of this lesson, you'll be able to:
:information_source: What is a Dictionary? A dictionary is a data structure that stores information using key-value pairs. Think of it like a real dictionary where you look up a word (key) to find its meaning (value)!
Dictionaries help us store data in a meaningful way. Let's see why they're better than lists for certain tasks.
Imagine you want to store information about a student. Using a list might look like this:
student = ["Sharvin", "M", 20]
What does each value mean? It's not clear! :emoji:
Python solves this problem with dictionaries:
student = {"name":"Sharvin", "gender":"M", "age":20}
Now we can see exactly what each piece of information means! :tada:
A dictionary has a simple structure:
{ }
: Contains all the key-value pairs,
: Separate each key-value pair:
: Connect each key to its valueKey | Value | Description |
---|---|---|
1 | "One" | The word for number 1 |
2 | "Two" | The word for number 2 |
3 | "Three" | The word for number 3 |
:memo: Important! Dictionaries don't keep items in order like lists do. Each item is found by its key, not by its position.
Let's learn the five main operations you can do with dictionaries:
Creating a dictionary is easy! Just use curly brackets and add your key-value pairs:
student = {
"name": "Chong Wei",
"gender": "M",
"age": 15
}
:bulb: Pro Tip! Write each key-value pair on a new line to make your dictionary easier to read! This makes it much easier to see what information you're storing.
There are several ways to get information from your dictionary. Let's explore each method!
To get a value, use the key inside square brackets []
:
student["name"]
student = {
"name":"Chong Wei",
"gender":"M",
"age":15
}
print(student["name"])
Expected output:
Chong Wei
Python gives us special methods to access different parts of a dictionary:
.items()
- Get all key-value pairs together (perfect for looping!).keys()
- Get all the keys only (useful to see what information is stored).values()
- Get all the values only (helpful for getting just the data)student.items()
student.keys()
student.values()
student = {
"name":"Chong Wei",
"gender":"M",
"age":15
}
print(student.items())
print(student.keys())
print(student.values())
Expected output:
dict_items([('name', 'Chong Wei'), ('gender', 'M'), ('age', 15)])
dict_keys(['name', 'gender', 'age'])
dict_values(['Chong Wei', 'M', 15])
Before using a key, you can check if it exists:
"gender" in student
student = {
"name":"Chong Wei",
"gender":"M",
"age":15
}
print("gender" in student)
Expected output:
True
:memo: Note This returns
True
if the key exists, andFalse
if it doesn't!
You can use a for
loop to go through all items:
for x in student.items():
print(x)
student = {
"name":"Chong Wei",
"gender":"M",
"age":15
}
for x in student.items():
print(x)
Expected output:
('name', 'Chong Wei')
('gender', 'M')
('age', 15)
Each item is printed as a tuple (a pair of values).
Changing a value is simple - just assign a new value to an existing key:
student["age"] = 16
print(student)
Expected output:
{'name': 'Chong Wei', 'gender': 'M', 'age': 16}
The age changed from 15 to 16! :emoji:
Adding a new item works the same way - just use a new key:
student["Program"] = "F"
print(student)
Expected output:
{'name': 'Chong Wei', 'gender': 'M', 'age': 16, 'program': 'F'}
Now the dictionary has a new key-value pair! :sparkles:
To remove an item, use the del
keyword:
del student["gender"]
print(student)
Expected output:
{'name': 'Chong Wei', 'age': 16, 'program': 'F'}
The "gender" key and its value are gone! :emoji:️
Sometimes you need to store complex data. You can put dictionaries inside dictionaries, or lists inside dictionaries!
Students | name | gender | age |
---|---|---|---|
student1 | Chong Wei | M | 15 |
student2 | Sharvin | M | 12 |
student3 | Yet Phing | F | 13 |
We can store this data in two ways:
Method 1: Dictionaries in Dictionary (Each student is a separate dictionary)
Students = {
"student1": {
"name":"Chong Wei",
"gender": "M",
"age":15
},
"student2": {
"name":"Sharvin",
"gender": "M",
"age":12
},
"student3": {
"name":"Yet Phing",
"gender": "F",
"age":13
}
}
Method 2: Lists in Dictionary (Each attribute contains a list of values)
Students = {
"name":["Chong Wei","Sharvin","Yet Phing"],
"gender":["M", "M", "F"],
"age":[15,12,13]
}
:bulb: Tip Both methods work! Choose Method 1 when you need to access all information about one student. Choose Method 2 when you need to work with one type of information for all students.
:emoji: Learn More: Nested Dictionary Tutorial
Dictionaries are powerful tools for organizing data:
Code with AI: Try using AI to work with dictionaries.
Prompts to try:
Try these exercises to master dictionaries:
.keys()
, .values()
, and .items()
:memo: Remember! Dictionaries are like labeled boxes - each label (key) helps you find exactly what you're looking for (value). Practice makes perfect! :star2: