x = {'a': {'b': 5, 'c': 6}, 'c':{'d': 10}}
new_x = {a:{'e' if c == 'c' else c:4 if c == 'c' else d for c, d in b.items()} for a, b in x.items()}
输出:
{'a': {'b': 5, 'e': 4}, 'c': {'d': 10}}
或者,使用递归遍历深度未知的字典:
x = {'a': {'b': 5, 'c': 6}, 'c':{'d': 10}}
def update_dict(target, **to_become):
return {a:{to_become.get(c, c):to_become['new_val'] if c in to_become else d for c, d in b.items()} if all(not isinstance(h, dict) for e, h in b.items()) else update_dict(b, **to_become) for a, b in target.items()}
print(update_dict(x, c = 'e', new_val = 4))
你可以使用字典理解:
输出:
或者,使用递归遍历深度未知的字典:
输出:
你想做的不是替代品。这是两次手术。你知道吗
c
键:del x['a']['c']
x['a']['e']=4
要替换同一个键的值,只需将一个新值赋给键
x['a']['c']=15
相关问题 更多 >
编程相关推荐