Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a dictionary from another dictionary python

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:

  1. It will be great if the solution is a one liner or something which do not takes a for loop.
  2. Also we need not to check whether parent dictionary has the key before deleting, since the child dictionary is derived from the parent dictionary. So need not think about keyError.
  3. The parent dictionary is a static dictionary which should not be affected by the method. Instead the returning dictionary should be stored in another reduced dictionary.
  4. There is no need to check whether the child_dict has same key as that of parent_dict. Only the key matters.
like image 547
thiruvenkadam Avatar asked Oct 31 '25 19:10

thiruvenkadam


1 Answers

{k: v for k, v in parent_dict.items() if k not in derived_dict}
like image 164
DrTyrsa Avatar answered Nov 02 '25 11:11

DrTyrsa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!