Dictionaries are a fundamental part of Python programming, providing a powerful way to manage and manipulate data through key-value pairs. Practicing dictionary exercises enhances your understanding of data handling, efficient lookups, and code readability. This guide offers a series of hands-on exercises to sharpen your skills with Python dictionaries, specifically through Python dictionary exercises.

Why Practice Dictionary Exercises?
- Strengthen Core Concepts: Reinforce the basics of Python dictionaries by working on various exercises.
- Real-World Application: Simulate common tasks like data filtering, counting, and mapping through focused dictionary exercises.
- Problem-Solving: Develop logical thinking by solving different levels of exercises.
- Interview Preparation: Prepare for coding interviews that frequently feature dictionary-based problems, which you can practise through Python dictionary exercises.
Beginner-Level Exercises
1. Create and Print a Dictionary
Create a dictionary with three key-value pairs and print the dictionary. This is a great starting point for beginners practising Python dictionary exercises.
Example:
my_dict = {"name": "John", "age": 30, "city": "New York"} print(my_dict)
Output: {'name': 'John', 'age': 30, 'city': 'New York'}
2. Access Dictionary Items
Retrieve and print the value of a specific key. Use the get()
method to avoid errors if the key doesn’t exist.
Example:
print(my_dict.get("age")) # Output: 30 print(my_dict.get("gender", "Not specified")) # Output: Not specified
3. Add and Update Items
Add a new key-value pair and update an existing one. Such updates are common in Python dictionary exercises.
Example:
my_dict["gender"] = "Male" my_dict["age"] = 35 print(my_dict)
Output: {'name': 'John', 'age': 35, 'city': 'New York', 'gender': 'Male'}
Intermediate-Level Exercises
4. Loop Through a Dictionary
Print all keys and values using a loop.
Example:
for key, value in my_dict.items(): print(f"{key}: {value}")
Output:
name: John age: 35 city: New York gender: Male
5. Remove Items
Remove an item using the pop()
method and clear all items using the clear()
method.
Example:
my_dict.pop("age") print(my_dict) my_dict.clear() print(my_dict)
Output:
{'name': 'John', 'city': 'New York', 'gender': 'Male'} {}
6. Merge Dictionaries
Merge two dictionaries using the update()
method. Merging dictionaries is a useful skill covered in many Python dictionary exercises.
Example:
new_dict = {"country": "USA", "occupation": "Engineer"} my_dict.update(new_dict) print(my_dict)
Output: {'name': 'John', 'city': 'New York', 'gender': 'Male', 'country': 'USA', 'occupation': 'Engineer'}
Advanced-Level Exercises
7. Count Word Frequency
Count the frequency of each word in a string using a dictionary. This type of counting is typically found in advanced Python dictionary exercises.
Example:
text = "apple banana apple orange banana apple" frequency = {} for word in text.split(): frequency[word] = frequency.get(word, 0) + 1 print(frequency)
Output: {'apple': 3, 'banana': 2, 'orange': 1}
8. Nested Dictionary
Create a nested dictionary and access its elements.
Example:
student = { "name": "Alice", "grades": {"math": 90, "science": 85} } print(student["grades"]["math"])
Output: 90
9. Dictionary Comprehension
Use dictionary comprehension to create a dictionary of squares from 1 to 5. This exercise is a popular challenge in many Python dictionary exercises.
Example:
squares = {x: x**2 for x in range(1, 6)} print(squares)
Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Best Practices for Solving Exercises
- Use
get()
to handle missing keys safely while practising Python dictionary tasks. - Use dictionary comprehension for concise, readable code in your Python dictionary exercises.
- Avoid modifying dictionaries during iteration; copy them first if needed.
- Practice nested dictionaries to manage complex data structures.
Conclusion
Practicing Python dictionary exercises helps you develop a solid understanding of key-value data handling. By starting with simple tasks and gradually advancing to more complex problems, you’ll gain the skills needed to manipulate dictionaries effectively in real-world applications. Keep practising and continue with Python dictionary exercises to master dictionaries and elevate your Python programming expertise!
Learn More about python dictionary
Interview Questions:
1.How do you merge two dictionaries in Python? (Google)
In Python, you can merge two dictionaries using the update()
method. This method takes another dictionary as an argument and adds its key-value pairs to the existing dictionary. If a key already exists, the value will be updated. In Python 3.9 and later, you can also use the |
operator to merge dictionaries. For example, dict1 | dict2
returns a new dictionary containing the merged data.
2.How do you handle missing keys in a dictionary? (Microsoft)
The get()
method is commonly used to handle missing keys in a dictionary. This method returns the value for a specified key if it exists; otherwise, it returns a default value (or None
if not specified). This approach prevents errors like KeyError
that occur when accessing a non-existent key directly. For example, my_dict.get('key', 'default')
ensures safe access without crashing the program.
3.What is a nested dictionary, and how do you access elements in it? (Amazon)
A nested dictionary is a dictionary within another dictionary. This data structure allows for organizing data hierarchically. To access elements, you use multiple keys. For example, student = {"name": "John", "grades": {"math": 95}}
allows you to retrieve the math grade by using student['grades']['math']
. Nested dictionaries are useful for representing structured data like JSON objects.
4.How can you loop through a dictionary and modify its values? (Meta)
To loop through a dictionary and modify its values, you can use the items()
method to iterate over key-value pairs. By looping with for key, value in my_dict.items():
, you can update values directly by referencing the key, e.g., my_dict[key] = value * 2
. It is important to avoid modifying the structure (like adding or deleting keys) during iteration to prevent runtime errors.
5.Explain dictionary comprehension with an example. (Netflix)
Dictionary comprehension is a concise way to create dictionaries using a single line of code. It follows the format {key: value for key, value in iterable}
. For example, {x: x**2 for x in range(1, 6)}
creates a dictionary of squares from 1 to 5. This technique improves code readability and efficiency, making dictionary creation more streamlined.
Play with : Dictionary Exercises
Question
Your answer:
Correct answer:
Your Answers