🧾 Python Dictionaries
Estimated reading: 3 minutes 38 views

πŸ§ͺ 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" from 2023 to 2024.

βœ… 4. Safely Get a Key’s Value

print(car.get("owner", "Not Available"))

βœ… Explanation:

  • Uses .get() to avoid a KeyError and 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 in keyword 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_settings into defaults, 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() or in to 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Python Dictionary Exercises

Or Copy Link

CONTENTS
Scroll to Top