替换Python字典中的条目

2024-04-25 14:49:41 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我用Python创建一个字典

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

并将其中一个条目替换为:

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

我该怎么做?谢谢!你知道吗


Tags: 字典条目
2条回答

你可以使用字典理解:

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}}

你想做的不是替代品。这是两次手术。你知道吗

  1. 从dict中删除c键:del x['a']['c']
  2. 向dic添加新值:x['a']['e']=4

要替换同一个键的值,只需将一个新值赋给键x['a']['c']=15

相关问题 更多 >