30 Python Dictionary Exercises for Mastery
Explore these exercises to solidify your understanding of Python dictionaries. Each exercise is designed to cover various aspects of dictionary usage. Check the answers at the bottom of the page.
Exercises
- Create a dictionary named
contacts
with the keys"name"
,"phone"
, and"email"
. Initialize it with your own contact details. (Exercise 1) - Add a new key-value pair to the
contacts
dictionary where the key is"address"
and the value is your home address. (Exercise 2) - Update the
"phone"
number in thecontacts
dictionary to a new value. (Exercise 3) - Remove the
"email"
key from thecontacts
dictionary. (Exercise 4) - Write a function
create_book
that takes a list of book titles and returns a dictionary with the titles as keys andNone
as values. (Exercise 5) - Write a function
get_value
that takes a dictionary and a key, and returns the value associated with that key. Handle the case where the key might not exist. (Exercise 6) - Given a dictionary of fruits with their quantities, find and print the total quantity of all fruits. (Exercise 7)
- Create a dictionary
person
with nested dictionaries for"address"
and"contacts"
. Print the city from the nested"address"
dictionary. (Exercise 8) - Use the
fromkeys()
method to create a dictionary with keys"a"
,"b"
, and"c"
, and all values set to0
. (Exercise 9) - Write a program to merge two dictionaries into one. Print the resulting dictionary. (Exercise 10)
- Sort a dictionary by its keys and print the sorted dictionary. (Exercise 11)
- Use the
setdefault()
method to add a new key-value pair to a dictionary only if the key does not already exist. (Exercise 12) - Write a function that takes a dictionary and a key, and returns the key-value pair if it exists; otherwise, return
"Key not found"
. (Exercise 13) - Count the number of unique values in a dictionary and print the result. (Exercise 14)
- Use the
pop()
method to remove a specific key-value pair from a dictionary. Print the removed item and the updated dictionary. (Exercise 15) - Print all keys in the dictionary using the
keys()
method. (Exercise 16) - Print all values in the dictionary using the
values()
method. (Exercise 17) - Print all key-value pairs in the dictionary using the
items()
method. (Exercise 18) - Write a dictionary comprehension to create a dictionary of squares for numbers 1 through 10. (Exercise 19)
- Use the
copy()
method to create a copy of a dictionary and modify the copy without affecting the original. (Exercise 20) - Check if a specific key exists in the dictionary using the
in
operator and print a corresponding message. (Exercise 21) - Calculate the average of numerical values in a dictionary where the keys are names and the values are grades. (Exercise 22)
- Find the day with the highest temperature from a dictionary where the keys are days and the values are temperatures. (Exercise 23)
- Remove items from a dictionary where the value is
None
. (Exercise 24) - Print all key-value pairs in a formatted manner. (Exercise 25)
- Create a dictionary of cubes for numbers from 1 to 10 using dictionary comprehension. (Exercise 26)
- Merge multiple dictionaries into one, ensuring that values from the last dictionary overwrite earlier ones. (Exercise 27)
- Find the length of a dictionary (i.e., the number of key-value pairs). (Exercise 28)
- Count the occurrences of each character in a string and store the results in a dictionary. (Exercise 29)
- Swap the keys and values in a dictionary and print the new dictionary. (Exercise 30)
Answers
- Example dictionary:
contacts = {"name": "John Doe", "phone": "555-1234", "email": "[email protected]"}
- Update with address:
contacts["address"] = "123 Main St, Anytown, USA"
- Update phone number:
contacts["phone"] = "555-5678"
- Remove email:
del contacts["email"]
- Function to create book dictionary:
def create_book(titles):
return {title: None for title in titles} - Function to get value:
def get_value(dictionary, key):
return dictionary.get(key, "Key not found") - Total quantity of fruits:
fruit_dict = {"apple": 10, "banana": 5, "orange": 7}
total_quantity = sum(fruit_dict.values()) - Nested dictionary for person:
person = {"address": {"city": "New York", "zip": "10001"}, "contacts": {"phone": "555-1234", "email": "[email protected]"}}
print(person["address"]["city"]) - Create dictionary with
fromkeys()
:keys = ["a", "b", "c"]
new_dict = dict.fromkeys(keys, 0) - Merge dictionaries:
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged_dict = {**dict1, **dict2} - Sort dictionary by keys:
sorted_dict = dict(sorted(dictionary.items()))
- Add key-value pair with
setdefault()
:dictionary.setdefault("new_key", "default_value")
- Function to return key-value pair:
def find_pair(dictionary, key):
return dictionary.get(key, "Key not found") - Count unique values:
unique_values = len(set(dictionary.values()))
- Remove key-value pair with
pop()
:removed_item = dictionary.pop("key_to_remove")
print("Removed:", removed_item)
print("Updated Dictionary:", dictionary) - Print all keys:
for key in dictionary.keys():
print(key) - Print all values:
for value in dictionary.values():
print(value) - Print all key-value pairs:
for key, value in dictionary.items():
print(f"{key}: {value}") - Create dictionary of squares:
squares = {x: x**2 for x in range(1, 11)}
- Create copy of dictionary:
copied_dict = original_dict.copy()
- Check if key exists:
if "key" in dictionary:
print("Key exists") - Calculate average of grades:
grades = {"John": 85, "Alice": 90, "Bob": 78}
average = sum(grades.values()) / len(grades) - Find day with highest temperature:
temperatures = {"Monday": 70, "Tuesday": 75, "Wednesday": 80}
highest_day = max(temperatures, key=temperatures.get) - Remove items with
None
values:cleaned_dict = {k: v for k, v in dictionary.items() if v is not None}
- Print all key-value pairs formatted:
for key, value in dictionary.items():
print(f"Key: {key}, Value: {value}") - Create dictionary of cubes:
cubes = {x: x**3 for x in range(1, 11)}
- Merge multiple dictionaries:
dicts = [{"a": 1}, {"b": 2}, {"c": 3}]
merged_dict = {}
for d in dicts:
merged_dict.update(d) - Find dictionary length:
length = len(dictionary)
- Count character occurrences:
string = "hello world"
char_count = {char: string.count(char) for char in set(string)} - Swap keys and values:
swapped_dict = {v: k for k, v in dictionary.items()}