使用相同键的值向上一级更新嵌套字典值
Update nested dictionary value with same key's value one level up
考虑:
[{'x': 'ABC-1|ABD-5',
'y': 8,
'z': 2,
'aa': {'az': 0.1001692265},
'bb': {'z': 0.0816721693}}]
如何更新嵌套字典的相同键的值,使其变为:
[{'x': 'ABC-1|ABD-5',
'y': 8,
'z': 2,
'aa': {'az': 0.1001692265},
'bb': {'z': 2}}]
有什么想法吗?
编辑:寻找一个更动态的解决方案,我可以将其重新用于任何具有不同键的字典
这会做你想做的事:
a = {'x': 'ABC-1|ABD-5',
'y': 8,
'z': 2,
'aa': {'az': 0.1001692265},
'bb': {'z': 0.0816721693}}
a['bb']['z'] = 2
print(a)
看来你需要
>>> d[0]['bb']['z'] = d[0]['z']
如果你想对每个子键都这样做,那么试试听写理解
>>> {k:v if not isinstance(v, dict)
else {subkey: (subval if subkey not in d[0] else d[0][subkey])
for (subkey, subval) in v.items()}
for k,v in d[0].items()}
递归函数怎么样?
d = {
"x": "ABC-1|ABD-5",
"y": 8,
"z": 2,
"aa": {"az": 0.1001692265},
"bb": {"z": 0.0816721693},
}
def update(d, key, val):
d[key] = val
for k, v in d.items():
if isinstance(v, dict):
update(v, key, val)
update(d, "z", 2)
考虑:
[{'x': 'ABC-1|ABD-5',
'y': 8,
'z': 2,
'aa': {'az': 0.1001692265},
'bb': {'z': 0.0816721693}}]
如何更新嵌套字典的相同键的值,使其变为:
[{'x': 'ABC-1|ABD-5',
'y': 8,
'z': 2,
'aa': {'az': 0.1001692265},
'bb': {'z': 2}}]
有什么想法吗?
编辑:寻找一个更动态的解决方案,我可以将其重新用于任何具有不同键的字典
这会做你想做的事:
a = {'x': 'ABC-1|ABD-5',
'y': 8,
'z': 2,
'aa': {'az': 0.1001692265},
'bb': {'z': 0.0816721693}}
a['bb']['z'] = 2
print(a)
看来你需要
>>> d[0]['bb']['z'] = d[0]['z']
如果你想对每个子键都这样做,那么试试听写理解
>>> {k:v if not isinstance(v, dict)
else {subkey: (subval if subkey not in d[0] else d[0][subkey])
for (subkey, subval) in v.items()}
for k,v in d[0].items()}
递归函数怎么样?
d = {
"x": "ABC-1|ABD-5",
"y": 8,
"z": 2,
"aa": {"az": 0.1001692265},
"bb": {"z": 0.0816721693},
}
def update(d, key, val):
d[key] = val
for k, v in d.items():
if isinstance(v, dict):
update(v, key, val)
update(d, "z", 2)