0

I have a following list of dictionaries:

clusters=[{'A': [1.0, 1.0]}, {'C': [4.0, 4.0], 'D': [4.0, 5.0], 'B': [2.0, 1.0]}]

I have written a snippet of code to access one dictionary at a time from the list:

for index, value in enumerate(clusters):
        for key in value:

such that i get the following dictionaries;

{'A': [1.0, 1.0]}
{'C': [4.0, 4.0], 'D': [4.0, 5.0], 'B': [2.0, 1.0]}

What i am trying to do is find the average of ith element of the list value in the dictionary. For example: In the second dictionary;

x-position-average = (4.0+4.0+2.0)/3

and then assign that value to a dictionary as:

new_centroid = {"X": x-position-average,"Y": y-position-average,...}
Clint Whaley
  • 459
  • 2
  • 7
  • 18

2 Answers2

2

Use the "sum" method. Given a dictionary "D":

def average(D, i):
    # key iterates over all keys in the dictionary. 
    # D[key][i] is the ith element of the list whose key is "key"
    return sum(D[key][i] for key in D)/len(D)

This returns the average of the ith element of every list in D.

matanso
  • 1,284
  • 1
  • 10
  • 17
1

If you have a dictionary of points in dimension n the following function returns their centroid as a tuple:

def centroid(d,n):
    return tuple(statistics.mean(d[k][i] for k in d) for i in range(n))

For example, if

cluster = {'C': [4.0, 4.0], 'D': [4.0, 5.0], 'B': [2.0, 1.0]}

Then

>>> centroid(cluster,2)
(3.3333333333333335, 3.3333333333333335)

This uses the statistics module, which is relatively new in Python 3.

John Coleman
  • 51,337
  • 7
  • 54
  • 119