python - 如何使用任意长度的键更新 python 字典?

标签 python dictionary

我正在使用 python 2.4 更新一个非常复杂且可能未知的字典,并且键复杂但明确。例如,字典是:

dict1 = {
  'server' : {
    'index' : 0,
    'info' : {
      'ip' : '127.0.0.1',
      'user' : {
        'number' : 1001,
        'tel' : '123456'
      }
    }
  }
}

现在我想使用键'server'-'info'-'user'-'number'更新(删除或修改)它。

我想使用显式键列表来更新字典,而我只知道字典对象,除了它的内部数据,我该怎么办?

最佳答案

考虑

>>> def get_nested(d, keys):
...     return reduce(dict.get, [d] + keys)
... 
>>> def set_nested(d, keys, value):
...     get_nested(d, keys[:-1])[keys[-1]] = value
... 
>>> dict1 = {
...   'server' : {
...     'index' : 0,
...     'info' : {
...       'ip' : '127.0.0.1',
...       'user' : {
...         'number' : 1001,
...         'tel' : '123456'
...       }
...     }
...   }
... }
>>> 
>>> keys = 'server-info-user-number'.split('-')
>>> get_nested(dict1, keys)
1001
>>> set_nested(dict1, keys, 2555)
>>> dict1
{'server': {'info': {'ip': '127.0.0.1', 'user': {'tel': '123456', 'number': 2555}}, 'index': 0}}

关于python - 如何使用任意长度的键更新 python 字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31625270/

相关文章:

python - 按索引汇总 2darray

python - 导入错误 : cannot import name normalize

python - 如何从另一个用户在 linux 中运行命令行

python - 将两个等长列表合并成一个字典,映射一对多

python - 只获取最后的回溯而不使用 None 的 raise?

python - 选择换行符之间的值并将其存储到列表中

python - 将字典列表中的两个列表合并为一个

python - 使用字典来减少元组列表

ios - 字典不允许我将字符串附加到它的值

c - 没有线性搜索的 C 中的快速字典