Python:使用列表中的项目来更改嵌套式样本的dict中的值 [英] Python: Change values in dict of nested dicts using items in a list

查看:196
本文介绍了Python:使用列表中的项目来更改嵌套式样本的dict中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何根据列表的值来修改/创建嵌套类型的命令中的键/值,其中列表的最后一项是该字符串的值,而其余的项目将缩短到该列的值类型的字典?
这将是列表:

How would you modify/create keys/values in a dict of nested dicts based on the values of a list, in which the last item of the list is a value for the dict, and the rest of items reefer to keys within dicts? This would be the list:

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

这只会在解析命令行参数时出现问题。很明显,使用 dict_nested [key1] [key1.2] [key1.2.1] [value]

This would only be a problem in situations like when parsing command line arguments. It's obvious that modifying/creating this value within a script would be pretty easy using dict_nested["key1"]["key1.2"]["key1.2.1"]["value"].

这将是一个嵌套的词典:

This would be a nested dict of dicts:

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

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

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

I guess that in this case, something like a recursive function or a list comprehension would be required.

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

此外,如果 list_address 中的项目将会冻结到不存在的字典中的键他们应该被创建。

Also, if items in list_address would reefer to keys in non-existing dictionaries, they should be created.

推荐答案

单行:

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

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

Note: dict.get and operator.getitem would produce wrong exceptions here.

一个显式的for循环,如 Joel Cornett的答案可能更易读。

An explicit for-loop as in Joel Cornett's answer might be more readable.

如果您要创建不存在的中间词典:

If you want to create non-existing intermediate dictionaries:

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

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

If you want to override existing intermediate values that are not dictionaries e.g., strings, integers:

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



示例



Example

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]



测试



Tests

>>> 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:使用列表中的项目来更改嵌套式样本的dict中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆