π§ͺ 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 :
