18. Python Dictionary with Examples and Tips (Video in Khmer)
Learn Python dictionaries with simple examples. Create dictionaries, use methods, and work with nested data.
2026-10-25 ยท 3 min read
Hello friend! ๐ A dictionary keep information as key and value. Use a key to find its value.
In this post, I show you how to make and use dictionaries in Python. Easy and short. ๐
๐ Make a Dictionary
Use curly brackets {}. Write a key, then :, then its value.
person = {
"name": "Dara",
"age": 20,
"city": "Phnom Penh"
}
print(person)
Output:
{'name': 'Dara', 'age': 20, 'city': 'Phnom Penh'}
๐ฅ Video: Introduction to Dictionary in Python (Khmer)
๐ Get and Change Values
Use the key inside square brackets to get or change a value.
person = {"name": "Dara", "age": 20}
print(person["name"]) # Dara
person["age"] = 21
person["city"] = "Siem Reap"
print(person)
Use .get() if the key may not exist. It return None instead of an error:
print(person.get("email")) # None
print(person.get("email", "No email")) # No email
๐งฐ Useful Dictionary Methods
person = {"name": "Dara", "age": 20}
print(person.keys()) # dict_keys(['name', 'age'])
print(person.values()) # dict_values(['Dara', 20])
print(person.items()) # dict_items([('name', 'Dara'), ('age', 20)])
person.update({"age": 21})
print(person["age"]) # 21
person.pop("age")
print(person) # {'name': 'Dara'}
๐ฅ Video: Using Dictionary Methods (Khmer)
๐ Loop Through a Dictionary
Use .items() to get each key and value.
person = {"name": "Dara", "age": 20}
for key, value in person.items():
print(key, value)
Output:
name Dara
age 20
๐ฆ Nested Dictionary
A dictionary can keep another dictionary inside it.
students = {
"student1": {"name": "Dara", "score": 90},
"student2": {"name": "Mina", "score": 95}
}
print(students["student1"]["name"]) # Dara
print(students["student2"]["score"]) # 95
๐ฅ Video: Nested Dictionary in Python (Khmer)
โ Common Error
Using a key that does not exist can give KeyError:
person = {"name": "Dara"}
# print(person["age"]) # KeyError
Use .get() when the key may not be there:
print(person.get("age", 0)) # 0
๐ก Tips
- A dictionary use
key: valuepairs. - Use clear keys, like
"name"and"age". - Use square brackets to get or set a value.
- Use
.get()when a key may not exist. - Use
.items()to loop through keys and values. - Keys must be unique. A new value with the same key replace the old value.
- Use a nested dictionary to group related information.
โ Any Question?
Tell us in comment below! ๐
#Python #Dictionary #Dict #LearnPython #Beginner