Computer Science Researcher • Educator • Programming Instructor
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.
A dictionary is written using curly brackets {}.
student = {
"name": "Khalid",
"age": 38,
"country": "Saudi Arabia"
}
print(student)
print(type(student))
Output:
{'name': 'Khalid', 'age': 38, 'country': 'Saudi Arabia'}
You access a value using its key:
student = {
"name": "Khalid",
"age": 38,
"country": "Saudi Arabia"
}
print(student["name"])
print(student["age"])
Output:
Khalid
38
student = {
"name": "Khalid",
"age": 38
}
student["grade"] = "A"
print(student)
Output:
{'name': 'Khalid', 'age': 38, 'grade': 'A'}
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
1. What does a dictionary store?
Only numbers2. Which brackets are used to create a dictionary?
[]3. What will this code print?
student = {"name": "Ali", "age": 15}
print(student["age"])
"age"4. Which method helps you loop through both keys and values?
.sort()5. What is the output of this code?
student = {"name": "Sara"}
student["grade"] = "B"
print(student)
{"grade": "B"}