如何根据列表的值修改/创建嵌套dicts的dict中的键/值,其中列表的最后一项是dict的值,其余项目依赖于列表中的键类型的字典? 这将是列表:
list_adddress = [ "key1", "key1.2", "key1.2.1", "value" ]
在解析命令行参数时,这只会是一个问题。很明显,使用dict_nested["key1"]["key1.2"]["key1.2.1"]["value"]
在脚本中修改/创建此值非常简单。
这将是dicts的嵌套词典:
dict_nested = {
"key1": {
"key1.1": {
"...": "...",
},
"key1.2": {
"key1.2.1": "change_this",
},
},
"key2": {
"...": "..."
},
}
我想在这种情况下,需要像递归函数或列表推导这样的东西。
def ValueModify(list_address, dict_nested):
...
...
ValueModify(..., ...)
此外,如果list_address
中的项目会转到不存在的词典中的键,则应该创建它们。
答案 0 :(得分:9)
一衬垫:
keys, (newkey, newvalue) = list_address[:-2], list_address[-2:]
reduce(dict.__getitem__, keys, dict_nested)[newkey] = newvalue
注意:dict.get
和operator.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}]
答案 1 :(得分:3)
address_list = ["key1", "key1.1", "key1.2", "value"]
def set_value(dict_nested, address_list):
cur = dict_nested
for path_item in address_list[:-2]:
try:
cur = cur[path_item]
except KeyError:
cur = cur[path_item] = {}
cur[address_list[-2]] = address_list[-1]
答案 2 :(得分:1)
我认为这就像你在追求一样。
def ValueModify(l, d):
if l[0] not in d:
d[l[0]] = dict()
if isinstance(d[l[0]], dict):
ValueModify(l[1:], d[l[0]])
else:
d[l[0]] = l[1]
我正在使用isinstance
,这是类型检查,通常不是你在Python中做的事情,但它确实按预期设置了值。
- 已编辑 -
如果原始nested_dict
未完全填充,则在缺少的密钥检查中添加以设置嵌套值。
答案 3 :(得分:0)
这是一个递归解决方案。
def unravel(d, keys):
i = keys[0]
keys = keys[1:]
tmpDict = d[i]
if type(tmpDict) != type({}):
return tmpDict
else:
return unravel(tmpDict, keys)
答案 4 :(得分:0)
要插入新的键值对或更新对的值:
import copy
def update_nested_map(d, u, *keys):
d = copy.deepcopy(d)
keys = keys[0]
if len(keys) > 1:
d[keys[0]] = update_nested_map(d[keys[0]], u, keys[1:])
else:
d[keys[0]] = u
return d
试验:
>>> d = {'m': {'d': {'v': {'w': 1}}}}
>>> update_nested_map(d, 999, ['m', 'd', 'v', 'w'])
{'m': {'d': {'v': {'w': 999}}}}
>>> update_nested_map(d, 999, ['m', 'd', 'v', 'z'])
{'m': {'d': {'v': {'z': 999, 'w': 1}}}}
>>> update_nested_map(d, 999, ['m', 'd', 'l'])
{'m': {'d': {'v': {'w': 1}, 'l': 999}}}
>>> update_nested_map(d, 999, ['m','d'])
{'m': {'d': 999}}