This Python dictionary exercise aims to help Python developers to learn and practice dictionary operations. All questions are tested on Python 3.
Python dictionary is a mutable object, and it contains the data in the form of key-value pairs. Each key is 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.
Also Read:
This Python dictionary exercise includes the following: –
- It contains 10 dictionary questions and solutions provided for each question.
- Practice different dictionary assignments, programs, and challenges.
It covers questions on the following topics:
- Dictionary operations and manipulations
- Dictionary functions
- Dictionary comprehension
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.
- Read the complete guide to Python dictionaries to solve this exercise
Table of contents
- Exercise 1: Convert two lists into a dictionary
- Exercise 2: Merge two Python dictionaries into one
- Exercise 3: Print the value of key ‘history’ from the below dict
- Exercise 4: Initialize dictionary with default values
- Exercise 5: Create a dictionary by extracting the keys from a given dictionary
- Exercise 6: Delete a list of keys from a dictionary
- Exercise 7: Check if a value exists in a dictionary
- Exercise 8: Rename key of a dictionary
- Exercise 9: Get the key of a minimum value from the following dictionary
- Exercise 10: Change value of a key in a nested dictionary
Exercise 1: Convert two lists into a dictionary
Below are the two lists. Write a Python program to convert them into a dictionary in a way that item from list1 is the key and item from list2 is the value
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 2: Merge two Python dictionaries into one
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}
Show Solution
Python 3.5+
Other Versions
Exercise 3: Print the value of key ‘history’ from the below 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 4: 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 5: 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 6: 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 7: Check if a value exists in a dictionary
We know how to check if the key exists in a dictionary. Sometimes it is required to check if the given value is present.
Write a Python program to check if value 200 exists in the following 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 8: 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 9: Get 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 10: 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} }
fateme says
Q9. Another solution:
sample_dict = {
‘Physics’: 82,
‘Math’: 65,
‘history’: 75
}
for kv in sample_dict.items():
if kv[1] == min(sample_dict.values()):
print(kv[0])
Yashka says
Alternate solution
minValue = min(sample_dict.values())
for key in sample_dict.keys():
if sample_dict[key] == minValue:
print(key)
fateme says
Q4. Another solution:
employees = [‘Kelly’, ‘Emma’]
defaults = {“designation”: ‘Developer’, “salary”: 8000}
dic = {}
for i in employees:
dic[i] = defaults
print(dic)
Samuel Grace says
Create a dictionary called player that contains player name Jane, player punch 10, player heal 16, and player health 100.
saipriya K says
It really helps for beginners, thank you!
Mahesh Reddy says
exercise 9:
solution:
print(min(sample_dict))
(or)
print(mim(sample_dict.keys())
Mahesh Reddy says
print(min(sample_dict.keys())
Vishal Soni says
Question9….One liner.
sample_dict = {'Physics': 82, 'Math': 65, 'history': 75}
print(min(zip(sample_dict.keys(),sample_dict.values()))[0])
Wallax96 says
one 'shorter' liner : print(min(sample_dict))
Emilio says
The approach is wrong. That one is better: print(min(sample_dict.items())[0])
vini1955 says
Exercise #5 – an alternative approach – delete keys you don’t need
(please re-insert if they get stripped)
def delete_keys(d, *k):
for j in k:
del d[j]
print(d)
delete_keys(sample_dict, 'age', 'city')
Anuj Singh says
#Exercise 10: Change the value of a key in a nested dictionary
We don’t know the employee sequence of Brad, then we have to traverse each key-value pair and look out for the value where the name is Brad, and then update the salary.
My approach is like this. Any other compact solution is welcome every time.
emp_name = 'Brad'
new_salary=8500
for key,value in sample_dict.items():
for key1,value1 in value.items():
if value1 == emp_name:
value['salary']=new_salary
print(sample_dict)
TuanNG says
Question 9:
Serkan says
Q8
Nidhi Gautam says
{'name': 'Kelly', 'age': 25, 'salary': 8000, 'location': 'New york'}
This is the required output for this code snippet,
Thanks, Vishal great job
Noxie says
Solution Q9
Noxie says
anaconda says
Deji says
My Solution to Exercise 9
Exercise 9: Get the key of a minimum value from the following dictionary
uvy says
required output : “Math”
Rishikesh Shah says
Exercise 6
Rishikesh Shah says
Q 5:
alex says
RT says
Question 1 solution:
Danilo says
Question 3
Muskan Ray says
Hey, Thanks for your question and answers it’s an amazing blog.
Hareesh Dwivedi says
Answer it urgently
I have a question to ask
A given dictionary D where the key is of the form YYYY-MM-DD and its corresponding value is an integer returns a new dictionary such that 1.its key(type = String) is a Day
2. its corresponding value is an integer is the sum of values on that day
if the input dictionary does not have that particular day then its value is the mean of prev and next day
Write an algorithm to demonstrate the following assumptions:
1. input dictionary will have at least Monday and Sunday
2. Input Dictionary is a string within the range(1970-2100)
3. Input dictionary value is an integer within the range(-1,000,000-1,000,000)
suraj says
Exercise 2: Merge the following two Python dictionaries into one
Output:
Em lien says
my solution for Q9
Danilo says
it returns ‘history’ if all subject written lowercase
Derick Blacido says
My solution
Andylee says
Hi. I’m hoping someone can help me understand something about the solution for Problem #2. I’m wondering why thirty isn’t duplicated in the new dictionary since appears in both dictionaries and the code uses a complete copy of the first list and the entire second list.
Manthan says
Because Dictionary has unique values
Sirisha Yatham says
How to write a code for dictionary in python with letter I with 25 words
Akshay says
Hi Vishal,
Really nice questions, does helps a lot.
Adham Jubran says
A solution to question 9
Adham Jubran says
OR:
print(min(sample_dict.values()))
Umang says
Solution for the first exercise
sheena says
solution Q6:
sheena says
solution to Q5:
sheena says
sorry for above code. didnt realise we have to create a new dictionary so
here is my solution
sriram says
kindly tell us
how to fetch key by searching its value in dict
Vishal says
Hey sriram, I will add that exercise
sheena says
as in Q9 we r searching for key with min value..here is how i did it
Ningkumoni Sharma says
thanks for the alternate solution
Disema says
sample_dict = {
'Physics': 82,
'Math':65,
'history': 75
}
#get a key with min value
min_key = min(sample_dict.keys())
#get a minimum value
min_value = min(sample_dict.values())
print(min_key, ":", min_value)
Santu says
Really a good site for beginners.
can you please help me to understand what is the difference between
sampleDict.get
andsampleDict.get()
Rajiv says
hello!
In Exercise 6 #Solution
*why you write dash(-) after
sampleDict().keys()
Please explain thisAshish says
It’s not ‘dash’ it’s minus sign. May be
makes sense for you.
Danilo says
Hi,
it’s not a dash or a minus, it’s the set method ‘difference’ which returns the unique elements in the first set which is not in the second set.
same like writing
That’s it
Anna says
Hey,
There is a spelling mistake in exercise 8: “Renme key city to…”.
Also the solution for the exercise 8 is specified in the exercise description itself.
Please take a look.
Vishal says
Thank you, Anna, for letting me know. I have corrected the spelling mistake.
Anna says
Hi, seems like there is a minor issue in Exercise 4. Please take a look at it.
Here is what your and my solution return back:
So, the values of the “defaults” dictionary are returned in a reversed order. I assume the “defaults” dictionary values should be written with “:” sign instead of a “comma” sign, or should be specified as a list.
Vishal says
Hi Anna, This has been fixed. Thank you once again for your observations
Artem says
Hello!
Explain exercise#5 please or at least tell what to read
I don’t get the solution
Thank you in advance!
Vishal says
Hi Artem, Can you please check the updated question.