简体   繁体   中英

Python modify nested dictionary value at list of keys

I have a dictionary like:

{"value1": {}, "value2": {"value3": {}, "value4": {}, "value5": {"value6": {}}}}

And a list of keys:

["value2", "value4"]

How can I modify the dictionary such that the key "value4" (in the dictionary with the key "value2" ) is changed to "value4*" ? I only want the last key to be affected, so "value2" would not be changed.

I have tried using list(map(dictionary.get, keys)) but this does not do what I want.

Thanks in advance.

ps I have tried to keep this very short, please tell me if I have cut out too much.

You can use recursion:

new_d = ["value2", "value4"]
d = {"value1": {}, "value2": {"value3": {}, "value4": {}, "value5": {"value6": {}}}}
def update(data):
  return {a if a != new_d[-1] else f'{a}*':b if not isinstance(b, dict) else update(b) for a, b in data.items()}

print(update(d))   

Output:

{'value1': {}, 'value2': {'value3': {}, 'value4*': {}, 'value5': {'value6': {}}}}

Edit: without f-string :

def update(data):
  return {a if a != new_d[-1] else a+"*":b if not isinstance(b, dict) else update(b) for a, b in data.items()}

Other option but different logic.

Works on second level keys, it changes only value4 directly under value2 :

dct = {"value1": {}, "value2": {"value3": {}, "value4": {}, "value5": {"value4": {}}}}
keyz = ["value2", "value4"]

print(dct)

def append_star(dct, keyz):
  dct[keyz[0]][keyz[1] + '*'] = dct[keyz[0]][keyz[1]]
  del dct[keyz[0]][keyz[1]]

append_star(dct, keyz)

Or in this case, value2 directly under value2 , not value2 at the higher level:

dct = {"value1": {}, "value2": {"value2": {}, "value4": {}, "value5": {"value4": {}}}}
keyz = ["value2", "value2"]
{'value1': {}, 'value2': {'value4': {}, 'value5': {'value4': {}}, 'value2*': {}}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM