Home > Software design >  how to merge keys in dictionary outside of list?
how to merge keys in dictionary outside of list?

Time:10-29

hello im trying to get dictionary with same keys and merge its values and if there is a duplicate leave only one value of duplicate.

data = {"test1":["data1", "data2"],
   "test1":["data3", "data4", "data2"],
   "test2":["1data", "2data"],
   "test2":["3data", "4data", "2data"]
   }

desired_result = {"test1":["data1", "data2", "data3", "data4"],
                 "test2":["1data", "2data", "3data", "4data"]
                 }

any ideas how to get result?

CodePudding user response:

First you need create list of dict (because you can't have dictionary with same keys) then iterate over them and extend them to list with key of dict then use set for delete duplicated like below:

data = [{"test1":["data1", "data2"]},{"test1":["data3", "data4", "data2"]},{"test2":["1data", "2data"]},{"test2":["3data", "4data", "2data"]}]

from collections import defaultdict

rslt_out = defaultdict(list)
for dct in data:
    for k,v in dct.items():
        rslt_out[k].extend(v)
     

for k,v in rslt_out.items():
    rslt_out[k] = list(set((v)))
        
print(rslt_out)

output:

defaultdict(list,
            {'test1': ['data3', 'data4', 'data2', 'data1'],
             'test2': ['2data', '3data', '1data', '4data']})
  • Related