I'm trying to build up an dictionary based on a list with a dynamic size.
parts = [['Sect', 'H1'],
['Sect', 'P'],
['Sect', 'P[2]'],
['Sect[2]', 'Sect', 'H2']]
Should result in such a dictionary like:
{
"Sect": {
"H1": {
},
"P": {
},
"P[2]": {
},
},
"Sect[2]": {
"Sect": {
"H2": {
}
}
}
}
I can't get it. Any idea how to turn a list of dynamic size into a tree structured dictionary?
My approach so far:
for i, part in enumerate(parts):
if i == 0:
if part not in result:
result[part] = dict()
if i == 1:
if part not in result[parts[i-1]]:
result[parts[i-1]][part] = dict()
if i == 2:
if part not in result[parts[i-2]][parts[i-1]]:
result[parts[i-2]][parts[i-1]][part] = dict()
...
But this isn't a dynamic approach so far.
CodePudding user response:
Similar to quamrana's answer, but a bit terser with dict.setdefault
.
d = {}
for p in parts:
inner = d
for k in p:
inner = inner.setdefault(k, {})
print(d) # {'Sect[2]': {'Sect': {'H2': {}}}, 'Sect': {'P[2]': {}, 'P': {}, 'H1': {}}}
CodePudding user response:
The answer is iteration. You can iterate over a list of lists. And for each list you can iterate to produce hierarchical dict
s.
parts = [['Sect', 'H1'],
['Sect', 'P'],
['Sect', 'P[2]'],
['Sect[2]', 'Sect', 'H2']]
data = {}
for part in parts:
d = data # refer to a current dict
for key in part:
new_dict = d[key] if key in d else {}
d[key] = new_dict
d = new_dict # recurse down the nested dicts
print(data)