0

I have a list of dictionaries,

lst = [{'A':1,'B':2,'C':4},{'A':2,'B':2,'C':4},{'A':3,'B':2,'C':4}]

I want to merge this into one dictionary and put the values inside list if a key has different values.

desired output = {'A':[1,2,3},'B':2,'C':4}

I tried but it was resulting in something like,

{'A':[1,2,3},'B':[2],'C':[4]}
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Jennifer Therese
  • 1,105
  • 9
  • 17
  • 1
    IMHO the result you get is better, the function(s) consuming the result wont have to check if it is a number or a list – Dani Mesejo Jan 18 '23 at 11:40
  • @DaniMesejo But I want the resultant to be specific, if the values are different it should be list else it should be it's own datatype – Jennifer Therese Jan 18 '23 at 11:42
  • 2
    Just transform the result you have now, like this: `{ k : v if len(v) > 1 else v[0] for k, v in res.items()}` – Dani Mesejo Jan 18 '23 at 11:43

1 Answers1

1

You can use a defaultdict for this purpose:

from collections import defaultdict
lst =[{'A':1,'B':2,'C':4},{'A':2,'B':2,'C':4},{'A':3,'B':2,'C':4}]

d = defaultdict(list)

print(d)
#  defaultdict(list, {})

for x in lst:
  for k,v in x.items():
    d[k].append(v)

print(dict(d))

#  {'A': [1, 2, 3], 'B': [2, 2, 2], 'C': [4, 4, 4]}

To get your desired result:

{ k : v if len(set(v)) > 1 else v[0] for k, v in d.items()}

#  {'A': [1, 2, 3], 'B': 2, 'C': 4}
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44