Home > other >  how to change tuple key into multilevel dict
how to change tuple key into multilevel dict

Time:10-07

I have a dictionary that looks like this: d = {key1 : {(key2,key3) : value}, ...} so it is a dictionary of dictionaries and in the inside dict the keys are tuples.

I would like to get a triple nested dict: {key1 : {key2 : {key3 : value}, ...}

I know how to do it with 2 loops and a condition:

new_d = {}
for key1, inside_dict in d.items():
    new_d[key1] = {}
    for (key2,key3), value in inside_dict.items():
        if key2 in new_d[key1].keys():
            new_d[key1][key2][key3] = value
        else:
            new_d[key1][key2] = {key3 : value}

Edit: key2 values are not guaranteed to be unique. This is why I added the condition

It feels very unpythonic to me. Is there a faster and/or shorter way to do this?

CodePudding user response:

You could use the common trick for nesting dicts arbitrarily, using collections.defaultdict:

from collections import defaultdict

tree = lambda: defaultdict(tree)  
new_d = tree()

for k1, dct in d.items():
    for (k2, k3), val in dct.items():
        new_d[k1][k2][k3] = val

CodePudding user response:

If I understand the problem correctly, for this case you can wrap all the looping up in a dict comprehension. This assumes that your data is unique:

data = {"key1": {("key2", "key3"): "val"}}
{k: {keys[0]: {keys[1]: val}} for k,v in data.items() for keys, val in v.items()}
  • Related