如果我用Python创建一个字典,
x = {'a': {'b': 5, 'c': 6}, 'c':{'d': 10}}
并希望更换一个条目如下:
x = {'a': {'b': 5, 'e': 4}, 'c':{'d': 10}}
我怎样才能做到这一点?谢谢!
你想做的不是替代品。这是两个操作。
c
键:del x['a']['c']
x['a']['e']=4
中添加一个新值要替换相同键的值,只需为键x['a']['c']=15
指定一个新值即可
您可以使用字典理解:
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))
输出:
{'a': {'b': 5, 'e': 4}, 'c': {'d': 10}}