Python Dictionary Exercises

Each exercise includes a task and its expected output to test your skills.

Exercise 1: Access Value by Key

Task: Print the value of key "name" from the following dictionary:

person = {
 "name": "Alice",
 "age": 25,
 "city": "New York"
}
print(person["name"])

Output:

Alice

Exercise 2: Add a Key-Value Pair

person = {"name": "Alice", "age": 25}
person["email"] = "alice@example.com"
print(person)

Output:

{'name': 'Alice', 'age': 25, 'email': 'alice@example.com'}

Exercise 3: Update an Existing Value

person = {"name": "Alice", "age": 25}
person["age"] = 30
print(person)

Output:

{'name': 'Alice', 'age': 30}

Exercise 4: Loop Through Dictionary Keys and Values

fruits = {"apple": 2, "banana": 3, "cherry": 5}
for key, value in fruits.items():
   print(f"{key}: {value}")

Output:

apple: 2
banana: 3
cherry: 5

Exercise 5: Remove a Key

fruits = {"apple": 2, "banana": 3, "cherry": 5}
fruits.pop("banana")
print(fruits)

Output:

{'apple': 2, 'cherry': 5}

Exercise 6: Merge Two Dictionaries

dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
dict1.update(dict2)
print(dict1)

Output:

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Exercise 7: Check if Key Exists

person = {"name": "Alice", "age": 30, "city": "Paris"}
if "city" in person:
   print("Yes, 'city' is a key in the dictionary.")
else:
   print("No, 'city' is not in the dictionary.")

Output:

Yes, 'city' is a key in the dictionary.

Exercise 8: Nested Dictionary Access

student = {
 "name": "Bob",
 "skills": {
   "language": "Python",
   "level": "Intermediate"
 }
}
print(student["skills"]["language"])

Output:

Python

Exercise 9: Dictionary Length

info = {"name": "Alex", "age": 40, "country": "USA"}
print(len(info))

Output:

3

Exercise 10: Use get() to Avoid Error

person = {"name": "Alice", "age": 25}
print(person.get("email", "Not Provided"))

Output:

Not Provided