Write a function called Remove_keys (mydict, keylist) that accepts 3
two parameters: a dictionary called mydict and a list called keylist.
34
Remove _keys(mydict, keyist) should remove all the keys
contained in keylist from mydict and return dictionary:
d="key1": "value1", "key2" : "value2", "key3" : "value3", "key4"
:"value4
keys = l"key1", "key3", "key5"| if Remove_keys(d, keys) returns to a dictionary- "key2"value2", "key4": "valu
Answers
The given code is written in Python.
def Remove_keys(mydict,keylist):
for i in keylist:
mydict.pop(i,None)
return mydict
The above function takes a dictionary and list as parameter. Then, the keys present in both dictionary as well as in keylist are deleted from the dictionary using pop() function.
We can check our result by an example,
def Remove_keys(mydict,keylist):
for i in keylist:
mydict.pop(i,None)
return mydict
dictionary={1:'A', 2:'B',3:'C',4:'D',5:'E',6:'F'}
keylist=[1,2,4,5]
print("Original Dictionary:")
print(dictionary)
dictionary=Remove_keys(dictionary,keylist)
print("New Dictionary:")
print(dictionary)
Output:
Original Dictionary:
{1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F'}
New Dictionary:
{3: 'C', 6: 'F'}
See the attachment for output.