繁体   English   中英

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

[英]How do I merge dictionaries in list that have equal value and concate values that are not equal and keep other field in dict?

有字典列表,当两个或多个字典中的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"
    }
]

我想合并具有公共 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"
    }
]

您可以使用库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"
  }
]

编辑:固定列表到字符串

你应该像这样循环字典:

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)

您在 dictionary_aux 中有结果。 我希望它有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM