[英]How do I merge dictionaries in list that have equal value and concate values that are not equal and keep other field in dict?
there is list of dictionaries, when id in two or more dict are equal,names are equal too,but codes are different.有字典列表,当两个或多个字典中的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"
}
]
I want to merge dict that have common id, then i want to have this list as you can see:我想合并具有公共 ID 的 dict,然后我想拥有这个列表,如您所见:
[
{
"id" : 2.0,
"name":"x",
"code" : "12345,23456"
},
{
"id" : 4.0,
"name":"y",
"code" : "6767,55657"
},
{
"id" : 5.0,
"name":"z",
"code" : "567"
}
]
You can do this using the library pandas
.您可以使用库
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)
Output输出
[
{
"id": 2.0,
"name": "x",
"code": "12345,23456"
},
{
"id": 4.0,
"name": "y",
"code": "6767,55657"
},
{
"id": 5.0,
"name": "z",
"code": "567"
}
]
EDIT: Fixed List to String编辑:固定列表到字符串
You should loop through the dictionary like this:你应该像这样循环字典:
dictionary_aux = []
for elem in dictionary:
found = False
for new_elem in dictionary_aux:
if new_elem.id == elem.id:
new_elem.code = new_elem.code + "," elem.code
found = True
break
if not found:
dictionary_aux.append(elem)
You have the result in dictionary_aux.您在 dictionary_aux 中有结果。 I hope it helps.
我希望它有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.