我有一个嵌套列表示例:
[['fruit','apple'],['fruit','orange'],['fruit','banana'],['vegetable','cabbage'],['vegetable','carrot'],['drink','cola'],['drink','milk']]
我想将它们按如下格式分组到字典中:
{
"0": {
"food_type": "fruit",
"example": {
"0": "apple",
"1": "orange",
"2": "banana"
}
},
"1": {
"food_type": "vegetable",
"example": {
"0": "cabbage",
"1": "carrot",
}
}
}我首先创建了水果列表,其中包含了food_type fruit_list = ['fruit', 'vegetable', 'drink']的唯一值,并使用推断函数来添加键值对。
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产出:
{
'0': {'food_type': 'fruit', 'example': {}},
'1': {'food_type': 'vegetable', 'example': {}},
'2': {'food_type': 'drink', 'example': {}}
}但是,我在为example的值创建嵌套dict时遇到了问题。我试过itertools.groupby,但结果并不理想。希望有人能给我指点!非常感谢!!
发布于 2022-02-24 21:09:09
尝试:
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)指纹:
{
"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"}},
}https://stackoverflow.com/questions/71258216
复制相似问题