1

there is list of dictionaries:

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

I want to merge dict that have common id, then i want to have this list as you see:

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

is there any faster way can check all of this in for loop ?

Nozar Safari
  • 505
  • 4
  • 17
arezoo
  • 328
  • 3
  • 14

1 Answers1

2

you can build a dictionary that has as key your id value and the values are a list of codes with commune id, then you can build your desired output using a list comprehension:

from collections import defaultdict

result = defaultdict(list)
for d in my_list:
    result[d['id']].append(d['code'])

final_list = [{'id': k, 'code': ', '.join(v)} for k, v in result.items()]

print(final_list)

output:

[{'id': 2.0, 'code': '12345, 23456'},
 {'id': 4.0, 'code': '6767, 55657'},
 {'id': 5.0, 'code': '567'}]
kederrac
  • 16,819
  • 6
  • 32
  • 55
  • thanks alot.if there are other field that are equal in dict that have same id ,for example "name" key,how keep them?[ { "id" : 2.0, "code" : "12345","name":"x" }, { "id" : 2.0, "code" : "23456","name":"x" }] – arezoo Feb 07 '20 at 11:53