Home > front end >  A python program to filter dictionary
A python program to filter dictionary

Time:12-22

Write a python program to filter a dictionary based on values that are the multiples of 6 NOTE:

  • Take keys as strings and values as integers. Constraints: 1<=number of key value pairs<=10

Sample test case: keys : a,b,c,d,e,f values:1,2,3,4,5,6 {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6} {'f':6}

CodePudding user response:

You can use a dict comprehension.

d = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
res = {k:v for k,v in d.items() if v % 6 == 0}
print(res)

CodePudding user response:

old_dict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}

#or this it will work totally perfect

#old_dict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13}

print (f"Original dictionary is : {old_dict}")

print()

new_dict = {key:value for (key, value) in old_dict.items() if value % 6 == 0}

print(f"New dictionary with multiple of 6 is : {new_dict}")
  • Related