Python list for nested keys
3 answers
(Let's assume you have multiple pairs with multiple keys / values.)
You can use setdefault
to add nested dictionaries for the whole subkey if they don't already exist, continuing this new one each time for all but the last subkey. Then put the value in 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 can 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
+3
source to share