Python dictionary key returns a value, lambda function


Dictionary type sort transcripts


Method I. dictionary key value returned by

data1 = {"lili":80, "xiaoqiang":75, "yunyun":89, "yuanyuan":90, "wanghao":85}
list1 = []
list2 = []
for key, value in data1.items():
    list1.append(key)
    list1.append(value)
    list2.append(value)


list2 = sorted(list2,reverse = True)
for i in range(len(list2)):
    j = list1.index(list2[i]) # 字典通过值返回键
    print("{}:{}".format(list1[j-1], list2[i]))

Output Effect:
Here Insert Picture Description
Method II.

data1 = {"lili":80, "xiaoqiang":75, "yunyun":89, "yuanyuan":90, "wanghao":85}
ls = list(data1.items()) # 列表嵌套元组
print(ls)
ls.sort(key = lambda x:x[1], reverse = True)
for i in range(5):
    print("{}:{}".format(ls[i][0], ls[i][1]))

Output effect:
Here Insert Picture Description

Published 16 original articles · won praise 8 · views 1830

Guess you like

Origin blog.csdn.net/wayne6515/article/details/104409874