Python按value取字典中的top3
n = 3 data = {'John': 100, 'Erica': 40, 'Make':65, 'Tom': 80}
print(data) temp_list = sorted(data.items(), key= lambda item:item[1], reverse= True) top3_list = temp_list[: n] print(top3_list) top3_dict = {} for l in top3_list: top3_dict[l[0]] = l[1] print(top3_dict)
结果为:
{'John': 100, 'Erica': 40, 'Make': 65, 'Tom': 80} [('John', 100), ('Tom', 80), ('Make', 65)] {'John': 100, 'Tom': 80, 'Make': 65}
参考自:https://blog.csdn.net/u014662865/article/details/81807112