Python: Created Nested Dictionary From List Of Paths
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, {}),
Solution 1:
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 = {}
forpath, spec in paths:
parts = path.split('.')
d = specs
for p in parts[:-1]:
d = d.setdefault(p, {})
d[parts[-1]] = spec
If you have only two parts per path (ObjN
and partN
say), you could just do this:
specs = {}
forpath, spec in paths:
[obj, part] = path.split('.')
specs.setdefault(obj, {})[part] = spec
Post a Comment for "Python: Created Nested Dictionary From List Of Paths"