[Solved] Sorting a list based on associated scores [closed]


I would approach this as follows:

from collections import defaultdict # using defaultdict makes the sums easier

correlations = defaultdict(int) # default to int (i.e. 0)

for i1, i2, correl in strScoresDict: # loop through data
    correlations[i1] += correl # add score for first item
    correlations[i2] += correl # and second item

output = sorted(correlations, 
                key=lambda x: correlations[x], 
                reverse=True) # sort keys by value

Note, however, that the output is

output == ['item2', 'item1', 'item4', 'item3']

As the total correlations are

{'item1': 220, 'item3': 100, 'item2': 240, 'item4': 200}

You can read about defaultdict here.

solved Sorting a list based on associated scores [closed]