Dynamically delete an item from a nested dictionary

I have a nested dictionary, and I want to be able to remove an arbitrary key from it.

A dictionary might look like this:

D={'key1':{'key2':{'key3':'value3', 'key4':'value4'}, 'key5':'value5'}} 

But it can be of any size. The problem is that the keys must be taken from the "key list", for example, for example:

 key_list = ['key1', 'key2', 'key4'] 

key_list can be of arbitrary size and contain any dictionary keys in it.

Due to the above criteria, I cannot just use:

 del D['key1']['key2']['key4'] 

because I cannot know in advance which keys the key_list will contain.

So, what will the general code look like based on the contents of key_list , delete the corresponding element in the D dictionary?

+5
source share
2 answers

You can use for-loop to loop through the values ​​in key_list and go to the key_list from which you want to remove the element:

 sub = D # Start with the full dictionary for i in key_list[:-1]: sub = sub[i] # Move down a level 

In the end, sub will be the dictionary you want to change. All you have to do is:

 del sub[key_list[-1]] 

since key_list[-1] is the key to delete.

Below is a demo:

 >>> D={'key1':{'key2':{'key3':'value3', 'key4':'value4'}, 'key5':'value5'}} >>> key_list = ['key1', 'key2', 'key4'] >>> sub = D >>> for i in key_list[:-1]: ... sub = sub[i] ... >>> del sub[key_list[-1]] >>> D {'key1': {'key5': 'value5', 'key2': {'key3': 'value3'}}} >>> 

As you can see, this is equivalent to:

 >>> D={'key1':{'key2':{'key3':'value3', 'key4':'value4'}, 'key5':'value5'}} >>> del D['key1']['key2']['key4'] >>> D {'key1': {'key5': 'value5', 'key2': {'key3': 'value3'}}} >>> 

except that the solution is dynamic (without hard-coded keys).

+4
source

You can think of nested dictionaries as a dictionary with several keys. If you change your dict, then you decide when to remove the item. If part of the key is in the list of keys or any other criteria. Consider this:

 D={'key1':{'key2':{'key3':'value3', 'key4':'value4', 'key7':{'key8':'value8'}}, 'key5':'value5'}, 'key6': 'value6'} def multipart_key(d): dd = {} for k in d: if isinstance(d[k], dict): inner = multipart_key(d[k]) for kk in inner: dd[k+chr(124)+kk] = inner[kk] else: dd[k] = d[k] return dd key_list = ['key3', 'key7'] DD = multipart_key(D) newDD = DD.copy() for k in DD: for kk in k.split(chr(124)): if kk in key_list: del newDD[k] break print(DD) # {'key1|key2|key3': 'value3', 'key1|key5': 'value5', 'key6': 'value6', 'key1|key2|key7|key8': 'value8', 'key1|key2|key4': 'value4'} print(newDD) # {'key1|key5': 'value5', 'key6': 'value6', 'key1|key2|key4': 'value4'} 
0
source

Source: https://habr.com/ru/post/1207852/


All Articles