Lesson 11 – Dictionaries

A dictionary stores data using key–value pairs. Instead of referring to data by index like lists, dictionaries use meaningful keys such as "name", "age", or "country". Dictionaries are extremely useful when storing structured information.

What Does a Dictionary Look Like?

A dictionary is written using curly brackets {}.

Example 1: Creating a Dictionary

student = {
    "name": "Khalid",
    "age": 38,
    "country": "Saudi Arabia"
}

print(student)
print(type(student))
        

Output:

{'name': 'Khalid', 'age': 38, 'country': 'Saudi Arabia'}

        

Example 2: Accessing Values

You access a value using its key:

student = {
    "name": "Khalid",
    "age": 38,
    "country": "Saudi Arabia"
}

print(student["name"])
print(student["age"])
        

Output:

Khalid
38
        

Example 3: Adding a New Key–Value Pair

student = {
    "name": "Khalid",
    "age": 38
}

student["grade"] = "A"

print(student)
        

Output:

{'name': 'Khalid', 'age': 38, 'grade': 'A'}
        

Example 4: Looping Through a Dictionary

You can loop through both keys and values:

student = {
    "name": "Khalid",
    "age": 38,
    "country": "Saudi Arabia"
}

for key, value in student.items():
    print(key, ":", value)
        

Output:

name : Khalid
age : 38
country : Saudi Arabia
        

Quiz: Test Your Understanding

1. What does a dictionary store?

Only numbers
Only text
Key–value pairs
Random data
Correct answer: Key–value pairs

2. Which brackets are used to create a dictionary?

[]
()
{}
<>
Correct answer: {}

3. What will this code print?

student = {"name": "Ali", "age": 15}
print(student["age"])
            
"age"
Ali
15
Error
Correct answer: 15

4. Which method helps you loop through both keys and values?

.sort()
.values()
.items()
.append()
Correct answer: .items()

5. What is the output of this code?

student = {"name": "Sara"}
student["grade"] = "B"
print(student)
            
{"grade": "B"}
{"name": "Sara"}
{"name": "Sara", "grade": "B"}
Error
Correct answer: {"name": "Sara", "grade": "B"}
Back to Top