centroids = defaultdict(float)
for i in range(k):
    len_best = len(bestmatches[i])
if len_best > 0:
    items = set.union(*[set(prefs[u].keys()) for u in bestmatches[i]])
for user_id in bestmatches[i]:
    row = prefs[user_id]
for m in items:
    if row[m] > 0.0:
        centroids[m] += row[m] / len_best
k-means clustering implementation in python, running out of memory