Dremendo Tag Line

Remove keys from a dictionary that contains in a list in Python

Dictionaries - Question 5

In this question, we will see how to remove the keys contains in the list b from the dictionary a in Python programming. To know more about dictionaries click on the dictionaries lesson.

A dictionary and a list are given below as:

    a={'maths':84, 'physics':92, 'computer':76, 'history':87, 'geography':64}
    b=['maths','geography','history']

Q5) Write a program in Python to remove the keys contains in the list b from the dictionary a. The output should be:

   {'physics':92, 'computer':76}

Program

a={'maths':84, 'physics':92, 'computer':76, 'history':87, 'geography':64}
b=['maths','geography','history']

print('Dictionary a:',a)
print('List b:',b)

for i in range(len(b)):
    del a[b[i]]

print('Dictionary a:',a)

Output

Dictionary a: {'maths': 84, 'physics': 92, 'computer': 76, 'history': 87, 'geography': 64}
List b: ['maths', 'geography', 'history']
Dictionary a: {'physics': 92, 'computer': 76}
video-poster