首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:使用groupby创建嵌套字典

Python:使用groupby创建嵌套字典
EN

Stack Overflow用户
提问于 2022-02-24 21:02:36
回答 1查看 225关注 0票数 1

我有一个嵌套列表示例:

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

我想将它们按如下格式分组到字典中:

代码语言:javascript
复制
{
    "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']的唯一值,并使用推断函数来添加键值对。

代码语言:javascript
复制
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

产出:

代码语言:javascript
复制
{
'0': {'food_type': 'fruit', 'example': {}}, 
'1': {'food_type': 'vegetable', 'example': {}}, 
'2': {'food_type': 'drink', 'example': {}}
}

但是,我在为example的值创建嵌套dict时遇到了问题。我试过itertools.groupby,但结果并不理想。希望有人能给我指点!非常感谢!!

EN

回答 1

Stack Overflow用户

发布于 2022-02-24 21:09:09

尝试:

代码语言:javascript
复制
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)

指纹:

代码语言:javascript
复制
{
    "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"}},
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71258216

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档