Reputation: 4250
If A and B are two dictionaries, using python, is there any way of removing elements from Dictionary A that are in dictionary B?
For example,
parent_dict = {"a" : "aaa", "b" : "bbb", "c" : "ccc", "d" : "ddd", "e": "eee"}
derived_dict = {"a" : "aaa", "d" : "ddd", "e" : "eee"}
Now I need to write a function dict_reduce(dictA, dictB) which deletes all the elements of dictB from dictA.
(i.e.,) dict_reduce(parent_dict, derived_dict) should give {"b" : "bbb", "c" : "ccc"}
My work around with a for loop is:
def dict_reduce(parent_dict, child_dict):
for key in child_dict.keys():
del parent_dict[key]
return parent_dict
reduced_dict = dict_reduce(parent_dict, child_dict)
NOTE:
Upvotes: 4
Views: 13706
Reputation: 343
Using the dictionaries provided in the question:
dict(parent_dict.items() - derived_dict.items())
or
dict(parent_dict.items() ^ derived_dict.items())
Upvotes: 7
Reputation: 12395
If affect parent_dict
is what you want this does the job
map(parent_dict.pop, filter(lambda k: k in derived_dict, parent_dict))
(and also returns duplicate keys)
This variant will also check (if requiered) that also values match:
map(parent_dict.pop, filter(lambda k: k in derived_dict and derived_dict[k] == parent_dict[k], parent_dict))
Upvotes: 0