Skip to content
Advertisement

make nested dict from list of chains (python)

everyone. I have the structure like this:

data = [
    ["apple", "1 apple", "2 apple"],
    ["lemon", "1 lemon", "2 lemon", "3 lemon"],
    ["lemon", "1 orange"]
]

And want the output like this:

{
    "apple": {
        "1 apple": {
            "2 apple": 0
        }
    },
    "lemon": {
        "1 lemon": {
            "2 lemon": {
                "3 lemon": 0
            }
        },
        "1 orange": 0
    },
}

I have a lot of of lists (chains) in the data, so I need your help!) How to do it in python?

Advertisement

Answer

Source : How to merge dictionaries of dictionaries?

def merge(a, b, path=None):
    "merges b into a"
    if path is None: path = []
    for key in b:
        if key in a:
            if isinstance(a[key], dict) and isinstance(b[key], dict):
                merge(a[key], b[key], path + [str(key)])
            elif a[key] == b[key]:
                pass # same leaf value
            else:
                raise Exception('Conflict at %s' % '.'.join(path + [str(key)]))
        else:
            a[key] = b[key]
    return a

def construct(data):
  if len(data) == 1:
    return {data[0]: 0}
  return {data[0]: construct(data[1:])}

res = {}
for item in data:
  a = construct(item)
  res = merge(res, a)
  print(res)
res
Advertisement