I have a dictionary that looks like this..
results = {'agunii2035': ['agunii3007', 'agunii2006', 'agunii2003', 'agunii3000'], 'agunii3007': ['agunii2035', 'agunii2006', 'agunii2003', 'agunii3000'], 'agunii2006': ['agunii2035', 'agunii3007', 'agunii2003', 'agunii3000'], 'agunii2003': ['agunii2035', 'agunii3007', 'agunii2006', 'agunii3000'], 'agunii3000': ['agunii2035', 'agunii3007', 'agunii2006', 'agunii2003']}
and I have another dictionary with some score like this..
score = {'agunii2035': [4, 4, 1, 3], 'agunii3007': [4, 3, 3, 1], 'agunii2006': [4, 3, 2, 2], 'agunii2003': [1, 3, 2, 1], 'agunii3000': [3, 1, 2, 1]}
I want to sort the values of “results” dictionary based on values of “score” dictionary.
For example,
For the key ‘agunii2035’, the score dictionary has values [ 4,4,1,3]
. So, I want to sort the values of “results” dictionary for the same key as ['agunii3007', 'agunii2006', 'agunii3000','agunii2003']
instead of ['agunii3007', 'agunii2006', 'agunii2003', 'agunii3000']
.
Advertisement
Answer
results = {'agunii2035': ['agunii3007', 'agunii2006', 'agunii2003', 'agunii3000'], 'agunii3007': ['agunii2035', 'agunii2006', 'agunii2003', 'agunii3000'], 'agunii2006': ['agunii2035', 'agunii3007', 'agunii2003', 'agunii3000'], 'agunii2003': ['agunii2035', 'agunii3007', 'agunii2006', 'agunii3000'], 'agunii3000': ['agunii2035', 'agunii3007', 'agunii2006', 'agunii2003']} score = {'agunii2035': [4, 4, 1, 3], 'agunii3007': [4, 3, 3, 1], 'agunii2006': [4, 3, 2, 2], 'agunii2003': [1, 3, 2, 1], 'agunii3000': [3, 1, 2, 1]} ordered_results = {key:[item for _, item in sorted(zip(score.get(key), value), reverse=True)] for key, value in results.items()} print(ordered_results)
output
{'agunii2035': ['agunii3007', 'agunii2006', 'agunii3000', 'agunii2003'], 'agunii3007': ['agunii2035', 'agunii2006', 'agunii2003', 'agunii3000'], 'agunii2006': ['agunii2035', 'agunii3007', 'agunii3000', 'agunii2003'], 'agunii2003': ['agunii3007', 'agunii2006', 'agunii3000', 'agunii2035'], 'agunii3000': ['agunii2035', 'agunii2006', 'agunii3007', 'agunii2003']}