Subtract dict A from dict B (deep del)?

If I have a deeply nested dict, is there a built-in way to subtract / delete the list of "paths" (for example: keyA.keyB.key1, keyA.keyC.key2, etc.) or the keys of the second dict from the original dict? Or maybe there is a common module that has such functions?

+4
source share
3 answers

Another solution:

d = { 'A' : { 'C' : { 'D' : { 'E' : 4, }, 'F' : 5, }, }, 'B' : 2, } def DeepDictDel(path, dict): for key in path.split('.'): owner = dict dict = dict[key] del owner[key] print d # prints {'A': {'C': {'D': {'E': 4}, 'F': 5}}, 'B': 2} DeepDictDel('ACD', d) print d # prints {'A': {'C': {'F': 5}}, 'B': 2} 
+1
source

Here is a suggestion:

 D = { "keyA": { "keyB" : { "keyC" : 42, "keyD": 13 }, "keyE" : 55 } } def remove_path(dictionary, path): for node in path[:-1]: dictionary = dictionary[node] del dictionary[path[-1]] remove_path(D, ["keyA", "keyB", "keyD"]) print D # prints {'keyA': {'keyB': {'keyC': 42}, 'keyE': 55}} 

You probably want to introduce some kind of error checking.

+2
source

Just in case, the other answers are not what you are looking for, here is one that subtracts one dictionary from another.

 def subtract(a, b): """ Remove the keys in b from a. """ for k in b: if k in a: if isinstance(b[k], dict): subtract(a[k], b[k]) else: del a[k] 
+2
source

All Articles