Reputation: 1686
I have the following Python list:
[
['a.b.c.d.e.rollover', 0],
['a.b.c.d.e.f.rollover', 1],
['a.b.c.d.e.g.rollover', 0]
]
Suppose this list is extremely large (lots of elements !)
Is there an efficient way in Python to convert this into a multi-level dictionary like the following ?
{
'a': {
'b': {
'c': {
'd': {
'e': {
'rollover': 0,
'f': {
'rollover': 1
}
'g': {
'rollover': 0
}
}
}
}
}
}
}
}
}
Upvotes: 2
Views: 95
Reputation: 17263
You can utilize defaultdict
with lambda
that returns defaultdict
that uses the same lambda
:
from collections import defaultdict
l = [
['a.b.c.d.e.rollover', 0],
['a.b.c.d.e.f.rollover', 1],
['a.b.c.d.e.g.rollover', 0]
]
dd = lambda: defaultdict(dd)
res = dd()
for k, v in l:
d = res
keys = k.split('.')
# Add all the keys except the last one, d[x] will do since
# it forces default value to be generated
for x in keys[:-1]:
d = d[x]
# Assign value to last key
d[keys[-1]] = v
print res['a']['b']['c']['d']['e']['rollover'] # 0
print res['a']['b']['c']['d']['e']['f']['rollover'] # 1
Short explanation: In order to automatically generate a new defaultdict
in case that key doesn't exist we need a function (or lambda
) that returns such an object. Since defaultdict
constructor needs a parameter we have to provide a function that passes the parameter to defaultdict
. Every time that non-existing key is being dereferenced the function is called and it creates a new defaultdict
that will again call the same function in the future if required. This is called autovivification.
Upvotes: 5