Create new dictionary from a list of keys in Python
Dictionaries - Question 4
In this question, we will see how to create a new dictionary from the dictionary a having the keys contains in the list b in Python programming. To know more about dictionaries click on the dictionaries lesson.
A dictionary and a list are given below as:
a={'english':56, 'maths':84, 'physics':92, 'computer':76, 'history':87} b=['maths','computer','physics']
Q4) Write a program in Python to create a new dictionary from the dictionary a having the keys contains in the list b. The output should be:
{'maths': 84, 'computer': 76, 'physics': 92}
Program
a={'english':56, 'maths':84, 'physics':92, 'computer':76, 'history':87}
b=['maths','computer','physics']
print('Dictionary a:',a)
print('List b:',b)
c=dict()
for i in range(len(b)):
x=a.get(b[i])
if x!='None':
c[b[i]]=x
print('Dictionary c:',c)
Output
Dictionary a: {'english': 56, 'maths': 84, 'physics': 92, 'computer': 76, 'history': 87} List b: ['maths', 'computer', 'physics'] Dictionary c: {'maths': 84, 'computer': 76, 'physics': 92}