This Python dictionary exercise helps developers learn and practice dictionary operations.
A Python dictionary is a mutable object that stores data as key-value pairs, with each key separated from its value by a colon (:). Dictionary is the most widely used data structure, and it is necessary to understand its methods and operations.
This Python dictionary exercise contains 20 dictionary coding questions, programs, and challenges to solve.
Solutions and hints are provided for each question, and all solutions have been tested on Python 3.
Also Read:
When you complete each question, you get more familiar with the Python dictionary. Let us know if you have any alternative solutions. It will help other developers.
- Use Online Code Editor to solve exercise questions.
- To solve this exercise, refer to the complete guide on Python dictionaries.
Table of contents
- Exercise 1: Perform basic dictionary operations
- Exercise 2: Perform dictionary operations
- Exercise 3: Dictionary from Lists
- Exercise 4: Clear Dictionary
- Exercise 5: Merge two Python dictionaries into one
- Exercise 6: Count Character Frequencies
- Exercise 7: Access Nested Dictionary
- Exercise 8: Print the value of key ‘history’ from nested dict
- Exercise 9: Modify Nested Dictionary
- Exercise 10: Initialize dictionary with default values
- Exercise 11: Create a dictionary by extracting the keys from a given dictionary
- Exercise 12: Delete a list of keys from a dictionary
- Exercise 13: Check if a value exists in a dictionary
- Exercise 14: Rename key of a dictionary
- Exercise 15: Get the key of a minimum value
- Exercise 16: Change value of a key in a nested dictionary
- Exercise 17: Invert Dictionary
- Exercise 18: Sort Dictionary by Keys
- Exercise 19: Sort Dictionary by Values
- Exercise 20: Check if All Values are Unique
Exercise 1: Perform basic dictionary operations
Given:
my_dict = {'name': 'Alice', 'age': 35, 'city': 'New York'}Code language: Python (python)
Perform following operations on given dictionary
- Add New Key-Value Pair: Add a new key-value pair,
'profession': 'Doctor', to the dictionary and print the updated dictionary. - Modify Value: Change the value of the
agekey to 40 in the dictionary and print the updated dictionary. - Access Key: Print the value associated with the
citykey.
Expected Output:
Original dictionary: {'name': 'Alice', 'age': 35, 'city': 'New York'}
Updated dictionary after adding 'profession': {'name': 'Alice', 'age': 35, 'city': 'New York', 'profession': 'Doctor'}
Updated dictionary after modification: {'name': 'Alice', 'age': 40, 'city': 'New York', 'profession': 'Doctor'}
City: New York
+ Hint
- You can add a new key-value pair to a dictionary by simply assigning a value to a new key using square bracket notation.
- Same as above you can modify an existing value by assigning a new value to an existing key using square bracket notation.
+ Show Solution
Exercise 2: Perform dictionary operations
Given:
my_dict = {'name': 'Alice', 'age': 35, 'city': 'New York', 'profession': 'Doctor'}Code language: Python (python)
Perform following operations on given dictionary
- Remove Key-Value Pair : Remove the
professionkey-value pair from the dictionary. - Get Items (Key-Value Pairs): Print all key-value pairs (items) in the dictionary.
- Check if Key Exists in the dictionary
Expected Output:
Original dictionary: {'name': 'Alice', 'age': 35, 'city': 'New York', 'profession': 'Doctor'}
Updated dictionary after removing 'profession': {'name': 'Alice', 'age': 35, 'city': 'New York'}
Printing all key-value pairs:
name: Alice
age: 35
city: New York
Does 'age' exist? True
+ Hint
- Use the
delkeyword to remove a key-value pair from a dictionary by specifying the key. - Use dictionary method
items(), that returns a view object of all key-value pairs. You can iterate over this view. - Use the
inkeyword is to check for the existence of a key in a dictionary.
+ Show Solution
Exercise 3: Dictionary from Lists
Write a Python program to convert two Python lists into a dictionary where elements from the first list become keys and elements from the second list become values.
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]Code language: Python (python)
Expected output:
{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
Show Solution
Solution 1: The zip() function and a dict() constructor
- Use the
zip(keys, values)to aggregate two lists. - Wrap the result of a
zip()function into adict()constructor.
Solution 2: Using a loop and update() method of a dictionary
Exercise 4: Clear Dictionary
Clear all key-value pairs from a given dictionary and print it.
Given:
my_dict = {'name': 'Alice', 'age': 35, 'city': 'New York'}Code language: Python (python)
Expected Output:
{}
+ Hint
Use dictionary method clear() to remove all items.
+ Show Solution
Exercise 5: Merge two Python dictionaries into one
Write a code to merge two dictionaries into a new dictionary and print it.
Given:
dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}Code language: Python (python)
Expected output:
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
+ Hint
There are three ways
- Using the
update()method. - Using the dictionary unpacking operator (
**for Python 3.5+) - Simple concatenation with
|(Python 3.9+).
Show Solution
Python 3.5+
Other Versions
Exercise 6: Count Character Frequencies
Given a string, create a dictionary where keys are characters and values are their frequencies in the string.
Given:
string1 = 'Jessa'Code language: Python (python)
Expected Output:
Frequencies for 'Jessa': {'J': 1, 'e': 1, 's': 2, 'a': 1}
+ Hint
- First, iterate through each character in the string using
forloop. - For each character, check if it’s already a key in your frequency dictionary using
get()method. If it is, increment its count; otherwise, add it as a new key with a count of 1.
+ Show Solution
Exercise 7: Access Nested Dictionary
Given a nested dictionary {'person': {'name': 'Alice', 'age': 30}}, print Alice’s age.
Given:
data = {'person': {'name': 'Alice', 'age': 30}}Code language: Python (python)
Expected Output:
Alice's age is: 30
+ Hint
To access values in a nested dictionary, you use multiple sets of square brackets, chaining the key lookups for each level of nesting.
+ Show Solution
Explanation:
nested_person_dict['person']: This accesses the inner dictionary associated with the key'person'.['age']: This then accesses the'age'key within that inner dictionary.= 31: Finally, this assigns the new value31to the'age'key.
Exercise 8: Print the value of key ‘history’ from nested dict
sampleDict = {
"class": {
"student": {
"name": "Mike",
"marks": {
"physics": 70,
"history": 80
}
}
}
}
Code language: Python (python)
Expected output:
80
Show Hint
It is a nested dict. Use the correct chaining of keys to locate the specified key-value pair.
Show Solution
Exercise 9: Modify Nested Dictionary
In the below dictionary, change name to ‘Jessa’.
Given:
nested_student_dict = {
"class": {
"student": {
"name": "Mike",
"marks": {
"physics": 70,
"history": 80
}
}
}
}Code language: Python (python)
Expected Output:
nested_student_dict = {
"class": {
"student": {
"name": "Jessa",
"marks": {
"physics": 70,
"history": 80
}
}
}
}
+ Hint
Use chained square bracket notation to reach the specific value you want to modify, then assign a new value to it.
+ Show Solution
Exercise 10: Initialize dictionary with default values
In Python, we can initialize the keys with the same values.
Given:
employees = ['Kelly', 'Emma']
defaults = {"designation": 'Developer', "salary": 8000}Code language: Python (python)
Expected output:
{'Kelly': {'designation': 'Developer', 'salary': 8000}, 'Emma': {'designation': 'Developer', 'salary': 8000}}
Show Hint
Use the fromkeys() method of dict.
Show Solution
The fromkeys() method returns a dictionary with the specified keys and the specified value.
Exercise 11: Create a dictionary by extracting the keys from a given dictionary
Write a Python program to create a new dictionary by extracting the mentioned keys from the below dictionary.
Given dictionary:
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"}
# Keys to extract
keys = ["name", "salary"]Code language: Python (python)
Expected output:
{'name': 'Kelly', 'salary': 8000}
Show Hint
- Iterate the mentioned keys using a loop
- Next, check if the current key is present in the dictionary, if it is present, add it to the new dictionary
Show Solution
Solution 1: Dictionary Comprehension
Solution 2: Using the update() method and loop
Exercise 12: Delete a list of keys from a dictionary
Given:
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"
}
# Keys to remove
keys = ["name", "salary"]Code language: Python (python)
Expected output:
{'city': 'New york', 'age': 25}
Show Hint
- Iterate the mentioned keys using a loop
- Next, check if the current key is present in the dictionary, if it is present, remove it from the dictionary
To achieve the above result, we can use the dictionary comprehension or the pop() method of a dictionary.
Show Solution
Solution 1: Using the pop() method and loop
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"
}
# Keys to remove
keys = ["name", "salary"]
for k in keys:
sample_dict.pop(k)
print(sample_dict)Code language: Python (python)
Solution 2: Dictionary Comprehension
Exercise 13: Check if a value exists in a dictionary
While we know how to check for a key’s presence in a dictionary, it’s sometimes necessary to determine if a specific value exists.
Write a Python program to check if the value 200 is present in the provided dictionary.
Given:
sample_dict = {'a': 100, 'b': 200, 'c': 300}Code language: Python (python)
Expected output:
200 present in a dict
Show Hint
- Get all values of a dict in a list using the
values()method. - Next, use the if condition to check if 200 is present in the given list
Show Solution
Exercise 14: Rename key of a dictionary
Write a program to rename a key city to a location in the following dictionary.
Given:
sample_dict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"
}Code language: Python (python)
Expected output:
{'name': 'Kelly', 'age': 25, 'salary': 8000, 'location': 'New york'}
Show Hint
- Remove the city from a given dictionary
- Add a new key (location) into a dictionary with the same value
Show Solution
Exercise 15: Get the key of a minimum value
Write a code to print the key of a minimum value from the following dictionary.
sample_dict = {
'Physics': 82,
'Math': 65,
'history': 75
}Code language: Python (python)
Expected output:
Math
Show Hint
Use the built-in function min()
Show Solution
Exercise 16: Change value of a key in a nested dictionary
Write a Python program to change Brad’s salary to 8500 in the following dictionary.
Given:
sample_dict = {
'emp1': {'name': 'Jhon', 'salary': 7500},
'emp2': {'name': 'Emma', 'salary': 8000},
'emp3': {'name': 'Brad', 'salary': 500}
}Code language: Python (python)
Expected output:
{
'emp1': {'name': 'Jhon', 'salary': 7500},
'emp2': {'name': 'Emma', 'salary': 8000},
'emp3': {'name': 'Brad', 'salary': 8500}
}
Show Solution
Exercise 17: Invert Dictionary
Write a code to swap keys and values in a dictionary. Assume all values are unique
Given:
original_dict1 = {'a': 1, 'b': 2, 'c': 3}Code language: Python (python)
Expected Output:
Original dictionary 1: {'a': 1, 'b': 2, 'c': 3}
Inverted dictionary 1: {1: 'a', 2: 'b', 3: 'c'}
+ Hint
- Remember that list indices start from 0. So, the third element will be at index 2. Use indexing to get a specific element.
- Use the
len()function to get the number of elements. - An empty list has a length of 0.
+ Show Solution
inverted_dict[value] = key: Inside the loop, for each pair, we take the value from the original dictionary and use it as the new key in inverted_dict, and the original key becomes its new value. This effectively swaps them.
Exercise 18: Sort Dictionary by Keys
Sort a dictionary by its keys and print the sorted dictionary (as an OrderedDict or by converting to a list of tuples).
Given:
my_dict = {'apple': 3, 'zebra': 1, 'banana': 2, 'cat': 4}Code language: Python (python)
Expected Output:
Original dictionary: {'apple': 3, 'zebra': 1, 'banana': 2, 'cat': 4}
Sorted by keys (as OrderedDict):
OrderedDict([('apple', 3), ('banana', 2), ('cat', 4), ('zebra', 1)])
+ Hint
You can get the keys, sort them, and then build a new dictionary or list of tuples.
+ Show Solution
Explanation:
my_dict_for_key_sort.items(): Gives us a list of(key, value)tuples.sorted(...): Sorts this list of tuples. By default,sorted()sorts tuples based on their first element (the key in this case).OrderedDict(...): Creates anOrderedDictfrom these sorted tuples. AnOrderedDictremembers the order in which items were inserted.
Or sorted(my_dict_for_key_sort.items()): This directly sorts the (key, value) tuples, giving you a list of tuples sorted by keys.
Exercise 19: Sort Dictionary by Values
Sort a dictionary by its values and print the sorted dictionary (as an OrderedDict or by converting to a list of tuples).
Given:
my_dict = {'Jessa': 3, 'Kelly': 1, 'Jon': 2, 'Kerry': 4, 'Joy': 1}Code language: Python (python)
Expected Output:
Original dictionary: {'Jessa': 3, 'Kelly': 1, 'Jon': 2, 'Kerry': 4, 'Joy': 1}
Sorted by values (as OrderedDict):
OrderedDict([('Jessa', 3), ('Kelly', 1), ('Jon', 2), ('Kerry', 4), ('Joy', 1)])
+ Hint
Use sorted() on the dictionary’s items, you’ll need to provide a key argument to sorted() to tell it to sort based on the second element of each (key, value) tuple (which is the value). You can use lambda function for this.
+ Show Solution
Exercise 20: Check if All Values are Unique
Write a function that takes a dictionary and returns True if all values in the dictionary are unique, False otherwise.
Given:
dict1 = {'a': 1, 'b': 2, 'c': 3} # All values unique
dict2 = {'x': 10, 'y': 20, 'z': 10} # Value 10 is duplicated
dict3 = {} # Empty dictionary (all values are vacuously unique)Code language: Python (python)
Expected Output:
Dictionary: {'a': 1, 'b': 2, 'c': 3} -> All values unique? True
Dictionary: {'x': 10, 'y': 20, 'z': 10} -> All values unique? False
Dictionary: {} -> All values unique? True
+ Hint
sets are excellent for checking uniqueness. You can extract all the values from the dictionary and then see if the number of values is the same as the number of unique values (i.e., the size of a set created from those values).
