Jue*_*mer 9 python dictionary key path
我有以下词典:
aDict = {
"a" : {
"b" : {
"c1" : {},
"c2" : {},
}
}
}
Run Code Online (Sandbox Code Playgroud)
第二个词:
aSecondDict = {
"d1" : {},
"d2" : {},
"d3" : {},
}
Run Code Online (Sandbox Code Playgroud)
和一个"路径"元组:
path = ( "a", "b", "c2" )
Run Code Online (Sandbox Code Playgroud)
我现在想要在元组提供的路径中将第二个dict添加到第一个dict:
aResultDict = {
"a" : {
"b" : {
"c1" : {},
"c2" : {
"d1" : {},
"d2" : {},
"d3" : {},
},
}
}
}
Run Code Online (Sandbox Code Playgroud)
实现这个目标的pythonic方法是什么?
mgi*_*son 12
您可以使用reduce1来获取字典并将dict.update新内容放入其中:
reduce(lambda d,key: d[key],path,aDict).update(aSecondDict)
Run Code Online (Sandbox Code Playgroud)
如果你愿意,你甚至可以更聪明一点:
reduce(dict.__getitem__,path,aDict).update(aSecondDict)
Run Code Online (Sandbox Code Playgroud)
我想应该指出的是,这两种方法略有不同.后者强制aDict只包含更多的字典(或dict子类),而前者允许任何有__getitem__方法的字典aDict. 如评论中所述,您还可以使用:
reduce(dict.get,path,aDict).update(aSecondDict)
Run Code Online (Sandbox Code Playgroud)
但是,AttributeError如果你尝试遍历路径中不存在的"链接",那么这个版本会引发一个,KeyError所以我不喜欢它.此方法还强制沿路径的每个值都是a dict或dict子类.
1reduce是python2.x的内置函数.从python2.6开始,它也可以作为functools.reduce.想要与python3.x兼容的代码应该尝试使用,functools.reduce因为在python3.x中删除了内置函数
| 归档时间: |
|
| 查看次数: |
2068 次 |
| 最近记录: |