'Python: Create nested dictionary using groupby

I have an example nested list:

[['fruit','apple'],['fruit','orange'],['fruit','banana'],['vegetable','cabbage'],['vegetable','carrot'],['drink','cola'],['drink','milk']]

I want to group them into dictionary in the format as:

{
    "0": {
        "food_type": "fruit",
        "example": {
            "0": "apple",
            "1": "orange",
            "2": "banana"
        }
    },
    "1": {
        "food_type": "vegetable",
        "example": {
            "0": "cabbage",
            "1": "carrot",
        }
    }
}

I first created fruit list, which contains the unique value of food_type fruit_list = ['fruit', 'vegetable', 'drink'] and used a function inference to add the key-value pairs

def inference(food_type, example):
    info = {"food_type": food_type, "example": {}}
    return info

result = []
for (idx_fruit, value_fruit) in enumerate(fruit_list):
    res = inference(value_fruit, {})
    result.append(res)

for idx, value in enumerate(result):
    result_dict[str(idx)] = value

output:

{
'0': {'food_type': 'fruit', 'example': {}}, 
'1': {'food_type': 'vegetable', 'example': {}}, 
'2': {'food_type': 'drink', 'example': {}}
}

But I had problem creating the nested dict for the value of example. I had tried itertools.groupby, but the result was not ideal. Hope someone can give me some guidance! Much thanks!!



Solution 1:[1]

Try:

from itertools import groupby


lst = [
    ["fruit", "apple"],
    ["fruit", "orange"],
    ["fruit", "banana"],
    ["vegetable", "cabbage"],
    ["vegetable", "carrot"],
    ["drink", "cola"],
    ["drink", "milk"],
]

out = {}
for i, (v, g) in enumerate(groupby(sorted(lst), lambda k: k[0])):
    out[str(i)] = {
        "food_type": v,
        "example": {str(i): v for i, (_, v) in enumerate(g)},
    }

print(out)

Prints:

{
    "0": {"food_type": "drink", "example": {"0": "cola", "1": "milk"}},
    "1": {
        "food_type": "fruit",
        "example": {"0": "apple", "1": "banana", "2": "orange"},
    },
    "2": {"food_type": "vegetable", "example": {"0": "cabbage", "1": "carrot"}},
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrej Kesely