Python Dictionary Exercises

Exercise 1: Create a Dictionary

Question

Create a dictionary of a student and print it.

Solution

student = {
"name": "Amit",
"age": 20,
"city": "Delhi"
}

print(student)

Exercise 2: Access Dictionary Item

Question

Print the value of "name" key.

Solution

print(student["name"])

Exercise 3: Safe Access Using get()

Question

Get the value of "marks" safely.

Solution

print(student.get("marks"))

Exercise 4: Change Dictionary Value

Question

Change the age to 21.

Solution

student["age"] = 21
print(student)

Exercise 5: Add New Item

Question

Add "marks" with value 85.

Solution

student["marks"] = 85
print(student)

Exercise 6: Remove Item Using pop()

Question

Remove "city" from dictionary.

Solution

student.pop("city")
print(student)

Exercise 7: Loop Through Dictionary

Question

Print all keys and values.

Solution

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

Exercise 8: Check Key Exists

Question

Check if "phone" key exists.

Solution

print("phone" in student)

Exercise 9: Count Dictionary Items

Question

Find how many items are in dictionary.

Solution

print(len(student))

Exercise 10: Copy Dictionary

Question

Create a copy of dictionary and change the copy.

Solution

student_copy = student.copy()
student_copy["name"] = "Ravi"

print(student)
print(student_copy)

Exercise 11: Nested Dictionary

Question

Create a nested dictionary of two students.

Solution

students = {
"s1": {"name": "Amit", "age": 20},
"s2": {"name": "Ravi", "age": 22}
}

print(students)

Exercise 12: Access Nested Dictionary Item

Question

Print age of student "s2".

Solution

print(students["s2"]["age"])

Exercise 13: Loop Nested Dictionary

Question

Print names of all students.

Solution

for s in students:
print(students[s]["name"])

Exercise 14: Use setdefault()

Question

Add "country" key with default value.

Solution

student.setdefault("country", "India")
print(student)

Exercise 15: Clear Dictionary

Question

Remove all items from dictionary.

Solution

student.clear()
print(student)

✅ Summary

✔ Dictionaries store key–value pairs
✔ Keys are unique
✔ Values can be changed
✔ Methods make work easy
✔ Practice improves skills

📘 Perfect for Beginner eBook

This exercise chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • Mini Python Projects

  • File Handling

  • Functions (easy)

  • If–Else Exercises

Just tell me 😊

You may also like...