Python:从路径列表创建嵌套字典 [英] Python: Created nested dictionary from list of paths
问题描述
我有一个看起来与此类似的元组列表(这里简化了,有超过 14,000 个这些元组的路径比 Obj.part 更复杂)
I have a list of tuples the looks similar to this (simplified here, there are over 14,000 of these tuples with more complicated paths than Obj.part)
[ (Obj1.part1, {
Obj 从 1 到 1000,从 0 到 2000 的部分.这些键"都有一个与之关联的规范字典,作为检查另一个二进制文件的查找参考.specs dict 包含路径 ObjK.partN 指向的数据的位偏移、位大小和 C 类型等信息.
Where Obj goes from 1 - 1000, part from 0 - 2000. These "keys" all have a dictionary of specs associated with them which act as a lookup reference for inspecting another binary file. The specs dict contains information such as the bit offset, bit size, and C type of the data pointed to by the path ObjK.partN.
例如:Obj4.part500 可能有这个规范,{'size':32, 'offset':128, 'type':'int'} 这会让我知道在二进制文件中访问 Obj4.part500我必须从偏移 128 解压 32 位.
For example: Obj4.part500 might have this spec, {'size':32, 'offset':128, 'type':'int'} which would let me know that to access Obj4.part500 in the binary file I must unpack 32 bits from offset 128.
所以,现在我想获取我的字符串列表并创建一个嵌套字典,在简化的情况下它看起来像这样
So, now I want to take my list of strings and create a nested dictionary which in the simplified case will look like this
data = { 'Obj1' : {'part1':{spec}, 'partN':{spec} },
'ObjK' : {'part1':{spec}, 'partN':{spec} }
}
为此,我目前正在做两件事,1. 我正在使用 dotdict 类,以便能够使用点表示法来获取/设置字典.该类看起来像这样:
To do this I am currently doing two things, 1. I am using a dotdict class to be able to use dot notation for dictionary get / set. That class looks like this:
class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
创建嵌套dotdict"的方法如下所示:
The method for creating the nested "dotdict"s looks like this:
def addPath(self, spec, parts, base):
if len(parts) > 1:
item = base.setdefault(parts[0], dotdict())
self.addPath(spec, parts[1:], item)
else:
item = base.setdefault(parts[0], spec)
return base
然后我就做类似的事情:
Then I just do something like:
for path, spec in paths:
self.lookup = dotdict()
self.addPath(spec, path.split("."), self.lookup)
所以,最后self.lookup.Obj4.part500
指向规范.
So, in the end
self.lookup.Obj4.part500
points to the spec.
有没有更好(更pythonic)的方法来做到这一点?
Is there a better (more pythonic) way to do this?
推荐答案
除非您更喜欢使用点表示法访问规范,否则请尝试将它们直接放入字典中.在下面的代码中,名称 d
跟踪路径上访问的最里面的字典:
Unless you prefer to access the specs with dot notation, try putting them into the dictionary directly. In the below code, the name d
tracks the innermost dictionary visited on the path:
specs = {}
for path, spec in paths:
parts = path.split('.')
d = specs
for p in parts[:-1]:
d = d.setdefault(p, {})
d[parts[-1]] = spec
如果每个路径只有两个部分(比如 ObjN
和 partN
),你可以这样做:
If you have only two parts per path (ObjN
and partN
say), you could just do this:
specs = {}
for path, spec in paths:
[obj, part] = path.split('.')
specs.setdefault(obj, {})[part] = spec
这篇关于Python:从路径列表创建嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!