Dictionary Exercises in Python with solution

Dictionary Exercises in Python: Dictionary in Python is also a type of data type like List. Each item in the dictionary is associated with a key ( paired in key, values ). Other programming languages use associative arrays for this approach.

These programming exercises have been structured and designed in a beginner-friendly way, focusing on the core concepts of Dictionary operations.

The main idea behind solving these questions is to make your concept clearer and improve logical thinking of approaching a problem. We are going to cover dictionary operations using some mix of conditional statements i.e if, if-else, for loop(), range(), while loop() etc.

For reference

dictionary exercises in python

Python Dictionary Exercises for beginners with Solution:

We will solve 15 python dictionary exercises for beginners in python with a solution & detailed code explanation.

Exercise 1: Write a program to check whether a given key exists in a dictionary or not.

Hint
Given dict = {‘0’:1, ‘1’:2, ‘2’:3}
Input:
Enter value to check: 2

Expected output 
Result: True

dict = {'0':1, '1':2, '2':3}
x = input("Enter value to check ")

if x in dict.keys():
    print(True)
else:
    print(False)

Exercise 2: Write a program to iterate over dictionary items using for loop.

Hint
dict = {0:”Value 1″, 1:”Value 2″}

Expected output
Value of key 0 is Value 1
Value of key 1 is Value 2

# iteration using fr loop
dict = {0:"Value 1", 1:"Value 2", 2:"Value 3"}

for key, val in dict.items():
    print(f" Value of key {key} is {val}")

Exercise 3: Write a program to print only keys of a dictionary.

Hint 
dict = {0:”Value 1″, 1:”Value 2″, 2:”Value 3″}

Expected output
Result: dict_keys([0, 1, 2])

# print all the keys of dictionary
dict = {0:"Value 1", 1:"Value 2", 2:"Value 3"}
keys = dict.keys()

# printing result
print(keys)

Exercise 4: Write a program to print values of dictionary.

Hint 
dict = {0:”Value 1″, 1:”Value 2″, 2:”Value 3″}

Expected output
dict_values([‘Value 1’, ‘Value 2’, ‘Value 3’])

# print only values
dict = {0:"Value 1", 1:"Value 2", 2:"Value 3"}
val = dict.values()

# printing result
print(val)

Exercise 5: Write a program in python to map 2 lists into a dictionary.

Hint 
Given keys = [1,2,3] values = [‘Value 1’, ‘Value 2’, ‘Value 3’]

Expected output
{1: ‘Value 1’, 2: ‘Value 2’, 3: ‘Value 3’}

# Given two list convert it into dict
keys = [1,2,3]
values = ['Value 1', 'Value 2', 'Value 3']

# zip function in dictionary
dict = dict(zip(keys, values))

# printing result
print(dict)

Exercise 6: Python program to remove a set of keys.

Note: If we remove the key of the dictionary then the respective values of the dictionary should also be deleted. This means there are no values that exist without keys.

Hint 
Given:
{0:”Value 1″, 1:”Value 2″, 2:”Value 3″}
keys_to_remove = [0,1]

Expected output
Result : {2: ‘Value 3’}

# delete a set of keys
dict = {0:"Value 1", 1:"Value 2", 2:"Value 3"}
keys_to_remove = [0,1]

dict = { k: dict[k] for k in dict.keys() - keys_to_remove }
print(dict)

Exercise 7: Python program to sort dictionary by values (Ascending/ Descending).

Hint 
Given
d = {‘key 1’: 2, ‘key 2’: 3, ‘key 3’: 4}

Expected output
Ascending: [(‘key 1’, 2), (‘key 2’, 3), (‘key 3’, 4)] Descending: [(‘key 3’, 4), (‘key 2’, 3), (‘key 1’, 2)]

# Sort dictionary in ascending / descending
import operator
d = {'key 1': 2, 'key 2': 3, 'key 3': 4}
print('Original dictionary : ',d)

# in ascending
sort_a = sorted(d.items(), key=operator.itemgetter(1))
print('In Ascending by value : ',sort_a)

# in descending
sort_d = sorted(d.items(), key=operator.itemgetter(1), reverse=True)
print('In Descending by value : ',sort_d)

Exercise 8: Write a program to concatenate two dictionaries to create one.

Hint 
Given
dict1 = {‘key 1’: 2, ‘key 2’: 3}
dict2 = {‘key 3’: 4, ‘key 4’: 5}

Expected output
{‘key 1’: 2, ‘key 2’: 3, ‘key 3’: 4, ‘key 4’: 5}

# Concatenate 2 dict to create one dict
dict1 = {'key 1': 2, 'key 2': 3}
dict2 = {'key 3': 4, 'key 4': 5}

# updating dict1 with dict2 using update method
dict1.update(dict2)

# changes made to dict1
# printing updated dict1
print(dict1)

Exercise 9: Write a program to sum all the values of a dictionary.

Hint 
dict1 = {‘key 1’: 200, ‘key 2’: 300}

Expected output
Result: 500

# Sum of dict values
dict1 = {'key 1': 200, 'key 2': 300}
x = []
for i in dict1.values():
    x.append(i)

# printing result
print(sum(x))

Exercise 10: Write a program to get the maximum and minimum value of dictionary.

Hint 
dict1 = {‘key 1’: 200, ‘key 2’: 300}

Expected output
Max: 300
Min: 200

# min and max of dict - values
dict1 = {'key 1': 200, 'key 2': 300}
val = dict1.values()
max = max(val)
min = min(val)

# printing result
print(f"{max} is maximum")
print(f"{min} is mimimum")

Exercise 11: Write a program to check if a dictionary is empty or not.

Hint 
Given dict1 = {}

Expected output
Is dictionary empty ? : True

# Dictionary is empty or not
# initialize empty dictionary
dict1 = {}

# using boolean if dictionary is empty
result = not bool(dict1)

# printing result
print("Is dictionary empty ? : " + str(result))

Exercise 12: Write a program in Python to choose a random item from a list.

Hint 
dict1 = {‘key 1’: 22, ‘key 2’: 301}
# we are checking for 22 value

Expected output
Value exists in dictionary

# value exist or not
dict1 = {'key 1': 22, 'key 2': 301}
val = dict1.values()

if 22 in val:
    print("Value exists in dictionary")
else:
    print("Value does not exist")

# Sameway we can check for keys

Exercise 13: Write a program to sort dictionary values in python.

Hint 
dict1 = {
‘key 1’: ‘Apple’, ‘key 2′:’Mango’,
‘key 3′:’Papaya’
}

Expected output
key 1: Apple
key 2: Mango
key 3: Papaya

# Sorting dictionary by value
dict1 = {
         'key 1': 'Apple',
         'key 2':'Mango',
         'key 3':'Papaya'
         }

for key in sorted(dict1):
    # printing result
    print("%s : %s" % (key, dict1[key]))

Exercise 14: Write a program to check whether a key exists in the dictionary or not.

Hint 
dict1 = {‘key 1’: 22, ‘key 2’: 301}

Expected output
Key exists in dictionary

# key exist or not
dict1 = {'key 1': 22, 'key 2': 301}
val = dict1.keys()

if 'key 2' in val:
    print("Key exists in dictionary")
else:
    print("Key does not exist")

#Sameway we can check for values

Exercise 15: Write a program in python to map keys to dictionary.

Hint 
key = [‘Fruit’, ‘Vegetable’] value = [‘Mango’,’Tomato’]

Expected output
{‘Fruit’: ‘Mango’, ‘Vegetable’: ‘Tomato’}

# Mapping keys to dictionary
key = ['Fruit', 'Vegetable']
value = ['Mango','Tomato']

dict1 = dict(zip(key, value))
# printing result
print(dict1)

Exercise 16: Write a program in Python to remove repetitive items from a list.

Hint 
Given num = [2,3,4,5,2,6,3,2]

Expected output
Result: [2, 3, 4, 5, 6]

num = [2,3,4,5,2,6,3,2]
x = []
for i in range(len(num)):
    if num[i] not in x:
        x.append(num[i])
    else:
        pass

# printing result
print(x)