1、使用 collections.defaultdict实现
from collections import defaultdictpN ={'dave': 10, 'jacinta': 10, 'james': 8, 'john': 6, 'jack': 3, 'sam': 2}#交换key和valuedct = defaultdict(list)for k, v in pN.items(): dct[v].append(k)#排序for k, v in sorted(dct.items(), reverse=True): print(k, ', '.join(v))#返回前n个元素def top_n(d, n): dct = defaultdict(list) for k, v in d.items(): dct[v].append(k) return sorted(dct.items())[-n:][::-1]top_n(pN, 3)
输出结果:
[(10, ['dave', 'jacinta']), (8, ['james']), (6, ['john'])]
2、使用max来实现
pN ={'dave': 10, 'jacinta': 10, 'james': 8, 'john': 6, 'jack': 3, 'sam': 2}def top_n_scores(n, score_dict): ''' returns the n scores from a name:score dict''' lot = [(k,v) for k, v in pN.items()] #make list of tuple from scores dict nl = [] while len(lot)> 0: nl.append(max(lot, key=lambda x: x[1])) lot.remove(nl[-1]) return nl[0:n] top_n_scores(4, pN)
输出结果:
[('dave', 10), ('jacinta', 10), ('james', 8), ('john', 6)]