Im trying to create/populate a nested dictionary from a list.
For example, a list [['a','b','c'],value] could create:
data['a']['b']['c'] = value
Giving me a dictionary:
{ 'a': { 'b': { 'c' : value } } }
All help greatly appreciated.
(Assuming that you have more than one of those multi-key/value pairs.)
You can use setdefault to add nested dictionaries for all the sub-key, unless they already exist, each time continuing with that new one for all but the last sub-key. Then put the value into the innermost dict.
def add_nested(d, keys, value):
for k in keys[:-1]:
d = d.setdefault(k, {})
d[keys[-1]] = value
Example:
values = [
[['a','b','c'], 1],
[['a','b','d'], 2],
[['a','e','f'], 3]]
result = {}
for keys, value in values:
add_nested(result, keys, value)
print(result)
Result:
{'a': {'b': {'c': 1, 'd': 2}, 'e': {'f': 3}}}
Alternatively, you could also use the good old infinite dictionary:
infinidict = lambda: collections.defaultdict(infinidict)
result = infinidict()
for keys, value in values:
last = reduce(operator.getitem, keys[:-1], result)
last[keys[-1]] = value
Python:
l = [['a', 'b', 'c'], 'foo']
d = l[1]
for k in l[0][::-1]:
d = {k : d}
print d
Output:
{'a': {'b': {'c': 'foo'}}}
d = l[1] then in the loop d = {k : d}?
d = {}; d['a', 'b', 'c'] = value