简体   繁体   中英

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" : 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" : 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 .

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. I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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