簡體   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