Home > Net >  Enhance groupby keys from list of dictionnaries into dictionnary
Enhance groupby keys from list of dictionnaries into dictionnary

Time:09-15

I want to go from

intput_dic = {"A":[{"a":11,"b":21,"c":31},{"a":12,"b":22,"d":24},{"a":18,"e":22,"d":24,"z":44}]} 

to

output_dic = {"A":{"a":[11,12,18],"b":[21,22],"c":[31],"d":[24,24],"z":[44]}}  

I write this code:

res_pp = {}
for (k, v) in intput_dic.items():
  merged_dict = {}
  for d in v:
    for kk, vv in d.items():
      if kk in merged_dict.keys():
        merged_dict[kk]  = [vv]
      else:
        merged_dict[kk] = [vv]
  res_pp[k] = merged_dict

Is there a better and more efficient way to do that ?

Thanks for your respond

CodePudding user response:

Using a helper function with dict.setdefault:

def flip(l):
    d = {}
    for d2 in l:
        for k,v in d2.items():
            d.setdefault(k, []).append(v)
    return d

output_dic = {k: flip(v) for k,v in input_dic.items()}

Output:

{'A': {'a': [11, 12, 18],
       'b': [21, 22],
       'c': [31],
       'd': [24, 24],
       'e': [22],
       'z': [44]}}

CodePudding user response:

def merge_dicts(data):
    result = {}
    for d in data:
        for k, v in d.items():
            result.setdefault(k, []).append(v)
    return result

merge_dicts(intput_dic['A'])
  • Related