0

I have a list of object like this.

data = [{123: 0.5}, {123: 0.6}, {23: 0.3}, {23: 0.2}]

if the key is duplicate then all values will be averaged like below.

[{123: 0.55}, {23: 0.25}]

I have tried using lambda but not getting any luck.

user3640472
  • 115
  • 9
  • could you include your try here? so that users can point out any mistake there? –  Jan 14 '22 at 18:57

3 Answers3

3

You can do this in two steps:

  1. Group the values in a dict of lists
  2. Get their averages and build the new list

Here I'm using a defaultdict(list) for step 1 since it makes it so simple:

from collections import defaultdict

groups = defaultdict(list)
for d in data:
    for k,v in d.items():
        groups[k].append(v)

out = [{k: sum(v)/len(v)} for k,v in groups.items()]
print(out)

Output:

[{123: 0.55}, {23: 0.25}]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
2

Are you going for anything efficient in particular. A quick bruteforce appraoch would look like this:

data = [{123: 0.5}, {123: 0.6}, {23: 0.3}, {23:0.2}]
my_dictionary = {}

for dictionary in data:
    for key in dictionary:
        if key in my_dictionary:
            my_dictionary[key].append(dictionary[key])
        else:
            my_dictionary[key] = [dictionary[key]]

for key in my_dictionary:
    my_dictionary[key] = sum(my_dictionary[key]) / len(my_dictionary[key])

print(my_dictionary)

Output would look like this:

{123: 0.55, 23: 0.25}

If you require a list of dictionaries, then you could create a list with each entry being they key of the dictionary above converted to a dict.

MiTriPy
  • 229
  • 1
  • 8
  • 1
    FWIW, [you can simplify the `if key in my_dictionary` part](/a/3483652/4518341). I posted [an answer](/a/70715598/4518341) myself that uses `defaultdict. – wjandrea Jan 14 '22 at 19:46
  • @wjandrea Checked and upvoted, thank you for sharing your idea, learned something new :D – MiTriPy Jan 15 '22 at 08:06
2

If you don’t mind using pandas:

import pandas as pd

dict(pd.DataFrame(data).mean())

It gives:

{23: 0.25, 123: 0.55}
bb1
  • 7,174
  • 2
  • 8
  • 23