本文介绍了使用密钥字符串列表作为路径添加到dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下dict:

aDict = {
    "a" : {
        "b" : {
            "c1" : {},
            "c2" : {},
        }
    }
}

第二个dict:

aSecondDict = { 
    "d1" : {},
    "d2" : {},
    "d3" : {},
}

和路径元组:

path = ( "a", "b", "c2" )

我现在要添加第二个dict到第一个由元组提供的路径:

I now want to add the second dict to the first at the path provided by the tuple:

aResultDict = {
    "a" : {
        "b" : {
            "c1" : {},
            "c2" : {
                "d1" : {},
                "d2" : {},
                "d3" : {},
            },
        }
    }
}

什么是pythonic的方式实现这个?

What is the pythonic way of achieving this?

推荐答案

你可以se reduce 获取字典和 dict.update 将新的东西放在在那里:

You can use reduce to get the dictionary and dict.update to put the new stuff in there:

reduce(lambda d,key: d[key],path,aDict).update(aSecondDict)

如果你愿意,你甚至可以更聪明一些:

You can even get a little more clever if you want:

reduce(dict.__getitem__,path,aDict).update(aSecondDict)

我想应该注意的是,这两种方法略有不同。后者强迫 aDict 只包含更多的字典(或 dict 子类),而前者允许任何具有 __ getitem __ 方法位于 aDict 中。 ,您还可以使用:

I suppose it should be noted that the two approaches are slightly different. The latter forces aDict to only contain more dictionaries (or dict subclasses) whereas the former allows for anything which has a __getitem__ method to be in aDict. As noted in the comments, you could also use:

reduce(dict.get,path,aDict).update(aSecondDict)

但是,如果你这样做,这个版本会引发一个 AttributeError 尝试遍历不存在的路径中的link,而不是 KeyError ,所以我不太喜欢它。该方法还强制,路径中的每个值都是 dict dict 子类。

However, this version will raise an AttributeError if you try to traverse a "link" in the path which is non-existent rather than a KeyError so I don't like it quite as much. This method also enforces that every value along the path is a dict or dict subclass.

reduce 是一个内置的python2.x。从python2.6开始,它也可以作为 functools.reduce 。希望与python3.x兼容的代码应该尝试使用 functools.reduce ,因为内置函数在python3.x中被删除

reduce is a builtin for python2.x. Starting at python2.6 it is also available as functools.reduce. Code which wants to be compatible with python3.x should try to use functools.reduce as the builtin is removed in python3.x

这篇关于使用密钥字符串列表作为路径添加到dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 12:46