[英]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*"
?如何修改字典,使键
"value4"
(在字典中的键为"value2"
)更改为"value4*"
? I only want the last key to be affected, so "value2"
would not be changed.我只希望最后一个键受到影响,因此不会更改
"value2"
。
I have tried using list(map(dictionary.get, keys))
but this does not do what I want.我试过使用
list(map(dictionary.get, keys))
但这不符合我的要求。
Thanks in advance.提前致谢。
ps I have tried to keep this very short, please tell me if I have cut out too much. ps我尽量保持简短,请告诉我是否剪掉了太多。
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
:编辑:没有
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
:适用于二级键,它仅在
value2
下直接更改value4
:
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:或者在这种情况下,
value2
直接位于value2
之下,而不是更高级别的value2
:
dct = {"value1": {}, "value2": {"value2": {}, "value4": {}, "value5": {"value4": {}}}}
keyz = ["value2", "value2"]
{'value1': {}, 'value2': {'value4': {}, 'value5': {'value4': {}}, 'value2*': {}}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.