dev.rean.me
python

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

Share:

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: value pairs.
  • 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


๐Ÿ“š Related Post

โ† Back to python
Share: