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!!