gpt4 book ai didi

python - 使用列表中的项目更改嵌套字典中的值?

转载 作者:太空狗 更新时间:2023-10-30 00:30:18 25 4
gpt4 key购买 nike

您将如何根据列表的值在嵌套字典的字典中修改/创建键/值,其中列表的最后一项是字典的值,其余项冷藏到键中听写?这将是列表:

list_adddress = [ "key1", "key1.2", "key1.2.1", "value" ]

这只会在解析命令行参数时出现问题。很明显,使用 dict_nested["key1"]["key1.2"]["key1.2.1"]["value"] 可以很容易地在脚本中修改/创建此值。

这将是一个嵌套的字典:

dict_nested = { 
"key1": {
"key1.1": {
"...": "...",
},
"key1.2": {
"key1.2.1": "change_this",
},
},

"key2": {
"...": "..."
},
}

我想在这种情况下,需要递归函数或列表理解之类的东西。

def ValueModify(list_address, dict_nested):
...
...
ValueModify(..., ...)

此外,如果 list_address 中的项目将引用到不存在的字典中的键,则应创建它们。

最佳答案

一行:

keys, (newkey, newvalue) = list_address[:-2], list_address[-2:]
reduce(dict.__getitem__, keys, dict_nested)[newkey] = newvalue

注意:dict.getoperator.getitem 会在这里产生错误的异常。

Joel Cornett's answer 中的显式 for 循环可能更具可读性。

如果你想创建不存在的中间字典:

reduce(lambda d,k: d.setdefault(k, {}), keys, dict_nested)[newkey] = newvalue

如果您想覆盖不是字典的现有中间值,例如字符串、整数:

from collections import MutableMapping

def set_value(d, keys, newkey, newvalue, default_factory=dict):
"""
Equivalent to `reduce(dict.get, keys, d)[newkey] = newvalue`
if all `keys` exists and corresponding values are of correct type
"""
for key in keys:
try:
val = d[key]
except KeyError:
val = d[key] = default_factory()
else:
if not isinstance(val, MutableMapping):
val = d[key] = default_factory()
d = val
d[newkey] = newvalue

例子

list_address = ["key1", "key1.2", "key1.2.1", "key1.2.1.1", "value"]
dict_nested = {
"key1": {
"key1.1": {
"...": "...",
},
"key1.2": {
"key1.2.1": "change_this",
},
},

"key2": {
"...": "..."
},
}

set_value(dict_nested, list_address[:-2], *list_address[-2:])
assert reduce(dict.get, list_address[:-1], dict_nested) == list_address[-1]

测试

>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> set_value(d, [], 'a', 1, OrderedDict) # non-existent key
>>> d.items()
[('a', 1)]
>>> set_value(d, 'b', 'a', 2) # non-existent intermediate key
>>> d.items()
[('a', 1), ('b', {'a': 2})]
>>> set_value(d, 'a', 'b', 3) # wrong intermediate type
>>> d.items()
[('a', {'b': 3}), ('b', {'a': 2})]
>>> d = {}
>>> set_value(d, 'abc', 'd', 4)
>>> reduce(dict.get, 'abcd', d) == d['a']['b']['c']['d'] == 4
True
>>> from collections import defaultdict
>>> autovivify = lambda: defaultdict(autovivify)
>>> d = autovivify()
>>> set_value(d, 'abc', 'd', 4)
>>> reduce(dict.get, 'abcd', d) == d['a']['b']['c']['d'] == 4
True
>>> set_value(1, 'abc', 'd', 4) #doctest:+IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError:
>>> set_value([], 'abc', 'd', 4) #doctest:+IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError:
>>> L = [10]
>>> set_value(L, [0], 2, 3)
>>> L
[{2: 3}]

关于python - 使用列表中的项目更改嵌套字典中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11918852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com