python中输出字典中值最大或最小的项
001、输出值最大的项
a、
>>> dict1 = {"c":30, "a":40, "b":80, "d":60} ## 测试字典 >>> dict1 {'c': 30, 'a': 40, 'b': 80, 'd': 60} >>> max_value = max(dict1.values()) >>> for i,j in dict1.items(): ... if j == max_value: ... print(i,j) ## 输出值最大的项 ... b 80
b、
>>> dict1 = {"c":30, "a":40, "b":80, "d":60} >>> dict1 {'c': 30, 'a': 40, 'b': 80, 'd': 60} >>> max(dict1.items(), key = lambda x:x[1]) ## 输出值最大的项 ('b', 80)
02、输出值最小的项
a、
>>> dict1 = {"c":30, "a":40, "b":80, "d":20, "e":60} ## 测试字典 >>> dict1 {'c': 30, 'a': 40, 'b': 80, 'd': 20, 'e': 60} >>> min_value = min(dict1.values()) >>> min_value 20 >>> for i,j in dict1.items(): ... if j == min_value: ... print(i, j) ## 输出值最小的项 ... d 20
b、
>>> dict1 = {"c":30, "a":40, "b":80, "d":20, "e":60} >>> dict1 {'c': 30, 'a': 40, 'b': 80, 'd': 20, 'e': 60} >>> min(dict1.items(), key = lambda x:x[1]) ## 输出值最小的项 ('d', 20)
。