Python Dictionary Exercises – Key-Value Practice with Examples
Introduction – Why Practice Dictionary Exercises?
Dictionaries in Python are used for storing and managing structured data in key-value format. Whether you’re building a form, working with APIs, parsing JSON, or tracking statistics, dictionaries are essential.
Practicing dictionary exercises helps reinforce:
- Value access & updates
- Key-value manipulations
- Iteration techniques
- Nested and real-world dictionary use
Basic Dictionary Exercises
1. Create a Dictionary and Print a Value
car = {"brand": "Tesla", "model": "Model 3", "year": 2023}
print(car["brand"])
Explanation:
- Accesses the value for the key
"brand"using square bracket syntax.
2. Add a New Key-Value Pair
car["color"] = "white"
print(car)
Explanation:
- Adds
"color"as a new key to the dictionary.
3. Change the Value of a Key
car["year"] = 2024
print(car)
Explanation:
- Updates the value of
"year"from2023to2024.
4. Safely Get a Key’s Value
print(car.get("owner", "Not Available"))
Explanation:
- Uses
.get()to avoid aKeyErrorand provide a fallback.
Intermediate Dictionary Exercises
5. Remove a Key from the Dictionary
car.pop("model")
print(car)
Explanation:
- Removes the
"model"key and its associated value.
6. Loop Through Keys and Values
for key, value in car.items():
print(f"{key} → {value}")
Explanation:
- Uses
.items()for key-value iteration.
7. Check if a Key Exists
if "brand" in car:
print("Brand is listed.")
Explanation:
- Uses the
inkeyword to verify if"brand"exists in the dictionary.
8. Merge Two Dictionaries
defaults = {"theme": "light", "volume": 50}
user_settings = {"theme": "dark"}
defaults.update(user_settings)
print(defaults)
Explanation:
- Merges
user_settingsintodefaults, overriding the"theme".
Advanced Dictionary Exercises
9. Use setdefault() to Set Missing Key
user = {"name": "Alice"}
user.setdefault("role", "User")
print(user)
Explanation:
- Inserts
"role": "User"if"role"key is not present.
10. Work with a Nested Dictionary
employees = {
"emp1": {"name": "John", "age": 28},
"emp2": {"name": "Jane", "age": 32}
}
print(employees["emp2"]["name"])
Explanation:
- Accesses a value inside a nested dictionary.
11. Count Occurrences of Characters in a String
text = "banana"
count = {}
for char in text:
count[char] = count.get(char, 0) + 1
print(count)
Explanation:
- Uses
.get()to count how many times each character appears.
12. Remove All Items from a Dictionary
car.clear()
print(car)
Explanation:
- Clears all entries, resulting in
{}.
Best Practices
- Use
.get()orinto safely access keys. - Prefer
.update()for merging configurations or responses. - Use
.setdefault()to initialize values only if they’re missing. - Avoid modifying dictionaries while iterating—use
.copy()if needed.
Summary – Recap & Next Steps
Python dictionaries are critical for handling structured, flexible key-value data. These exercises help solidify your understanding of core dictionary operations, from simple value access to nested lookups and conditionals.
Key Takeaways:
- Master accessing, adding, updating, and deleting keys
- Practice safe operations using
.get()and.setdefault() - Explore real-world usage with nested and merged dictionaries
Real-World Relevance:
Dictionaries power form processing, API parsing, settings storage, and object representation in Python applications.
FAQ Section – Python Dictionary Exercises
How do I avoid a KeyError when accessing a key?
Use .get() or check with "key" in dict.
What’s the fastest way to merge two dictionaries?
Use .update() or the |= operator (Python 3.9+):
dict1 |= dict2
How can I count frequencies with a dictionary?
Use .get() with a loop or collections.Counter.
How do I update a nested dictionary value?
Use chained keys:
dict["outer"]["inner"] = new_value
What is setdefault() used for?
To assign a default value to a key if it doesn’t already exist.
Share Now :
