gpt4 book ai didi

python - 如何合并列表中具有相等值的字典和不相等的连接值并将其他字段保留在字典中?

转载 作者:行者123 更新时间:2023-12-02 00:07:40 25 4
gpt4 key购买 nike

有字典列表,当两个或多个字典中的id相等时,名称也相等,但代码不同。

[
{
"id" : 2.0,
"name":"x",
"code" : "12345"
},
{
"id" : 2.0,
"name":"x",
"code" : "23456"
},
{
"id" : 4.0,
"name":"y",
"code" : "6767"
},
{
"id" : 5.0,
"name":"z",
"code" : "567"
},
{
"id" : 4.0,
"name":"y",
"code" : "55657"
}
]

我想合并具有公共(public) id 的字典,然后我想要这个列表,如您所见:

[
{
"id" : 2.0,
"name":"x",
"code" : "12345,23456"
},
{
"id" : 4.0,
"name":"y",
"code" : "6767,55657"
},
{
"id" : 5.0,
"name":"z",
"code" : "567"
}
]

最佳答案

您可以使用库 pandas 执行此操作。

import pandas as pd
# Here, L1 is your former list
L2 = pd.DataFrame(L1).groupby(["id", "name"], as_index=False).agg({"code": lambda x: ','.join(x.tolist())}).to_json(orient="records")
print(L2)

输出

[
{
"id": 2.0,
"name": "x",
"code": "12345,23456"
},
{
"id": 4.0,
"name": "y",
"code": "6767,55657"
},
{
"id": 5.0,
"name": "z",
"code": "567"
}
]

编辑:将列表固定为字符串

关于python - 如何合并列表中具有相等值的字典和不相等的连接值并将其他字段保留在字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60115364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com