【发布时间】:2020-09-10 06:35:47
【问题描述】:
我的目标是从嵌套字典中删除一个值。
假设我有字典:d = {'a': {'b': {'c': 10, 'd': 4}}}。
我知道我可以做到:del d['a']['b']['d']。
但我有一个长度未知的嵌套键列表。如果我有列表['a', 'b', 'd'],我想产生与上述相同的行为。问题是我不知道使用上述语法的键列表的长度。
要使用相同的输入访问一个值,这很简单:
def dict_get_path(dict_in: Dict, use_path: List):
# Get the value from the dictionary, where (eg)
# use_path=['this', 'path', 'deep'] -> dict_in['this']['path']['deep']
for p in use_path:
dict_in = dict_in[p]
return dict_in
但是我想不出任何类似的方法来删除一个项目而不重新构建整个字典。
【问题讨论】:
标签: python python-3.x dictionary