替换Python字典中的条目

问题描述 投票:0回答:2

如果我用Python创建一个字典,

x = {'a': {'b': 5, 'c': 6}, 'c':{'d': 10}}

并希望更换一个条目如下:

x = {'a': {'b': 5, 'e': 4}, 'c':{'d': 10}}

我怎样才能做到这一点?谢谢!

python dictionary
2个回答
4
投票

你想做的不是替代品。这是两个操作。

  1. 从你的词典中删除c键:del x['a']['c']
  2. 在dic:x['a']['e']=4中添加一个新值

要替换相同键的值,只需为键x['a']['c']=15指定一个新值即可


-1
投票

您可以使用字典理解:

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}}
© www.soinside.com 2019 - 2024. All rights reserved.