I would create an intermediate dictionary matching each name with the maximum rating for that name, and then return it to the descendants tuple:
>>> result = ({'name': 'xxx', 'score': 120L }, {'name': 'xxx', 'score': 100L}, {'name': 'xxx', 'score': 10L}, {'name':'yyy', 'score':20}) >>> from collections import defaultdict >>> max_scores = defaultdict(int) >>> for d in result: ... max_scores[d['name']] = max(d['score'], max_scores[d['name']]) ... >>> max_scores defaultdict(<type 'int'>, {'xxx': 120L, 'yyy': 20}) >>> tuple({name: score} for (name, score) in max_scores.iteritems()) ({'xxx': 120L}, {'yyy': 20})
Notes: 1) I added {'name': 'yyy', 'score': 20} to your example data to show that it works with a tuple with multiple names.
2) I am using defaultdict, which assumes that the minimum value for evaluation is zero. If the rating can be negative, you will need to change the int defaultdict (int) parameter to a function that returns a number less than the minimum possible score.
By the way, I suspect that having a dictionary tuple is not the best data structure for what you want to do. Have you considered alternatives, for example, having one dict, perhaps with a list of points for each name?
source share