简体   繁体   English

替换Python词典中的条目

[英]Replace entry in Python dictionary

If I create a dictionary in Python, 如果我用Python创建字典,

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

and would like to replace one entry as follows: 并希望替换一个条目,如下所示:

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

How can I do that? 我怎样才能做到这一点? Thanks! 谢谢!

What you want to do is not a replacement. 您要做的不是替代。 It's two operations. 这是两个操作。

  1. Delete c key from your dict: del x['a']['c'] 从您的字典中删除c键: del x['a']['c']
  2. Add a new value to the dic: x['a']['e']=4 向dic添加新值: x['a']['e']=4

To replace value of the same key, you just assign a new value to the key, x['a']['c']=15 要替换同一键的值,只需为该键分配一个新值x['a']['c']=15

You can use dictionary comprehension: 您可以使用字典理解:

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

Output: 输出:

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

Or, using recursion to transverse a dictionary of unknown depth: 或者,使用递归遍历未知深度的字典:

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

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM