python字典排序取最值总结
dic = {"abc":18,"adc":19,"abe":20} # 默认对键排序,从小到大,返回排序后键组成的列表 zidian = sorted(dic)#['abc', 'abe', 'adc'] print(zidian) # 对键进行反向(从大到小)排序 zidian = sorted(dic,reverse=True)#['adc', 'abe', 'abc'] print(zidian) # 拿到所有的key,然后再对key排序 zidian = sorted(dic.keys(),reverse=True)#['adc', 'abe', 'abc'] print(zidian) # 对值排序,从小到大 print(dic) zidian = sorted(dic.values())#[18, 19, 20] print(zidian) # 对值排序,从大到小 zidian = sorted(dic.values(),reverse=True)#[20, 19, 18] print(zidian) #可以用dict1.items(),得到包含键,值的元组, # 由于迭代对象是元组,返回值自然是元组组成的列表,x指元组,x[1]是值,x[0]是键 # 键由小到大排序 zidian = sorted(dic.items(),key=lambda x:x[0]) print(zidian) # 键由大到小排序 zidian = sorted(dic.items(),key=lambda x:x[0],reverse=True) print(zidian) # 值由小到大排序 zidian = sorted(dic.items(),key=lambda x:x[1]) print(zidian) # 值由大到小排序 zidian = sorted(dic.items(),key=lambda x:x[1],reverse=True) print(zidian) #itemgetter(0),获取key # itemgetter(1),获取value from operator import itemgetter d = {"a":8,"b":4,"c":12,"a":10,"b":1,"e":10} # 键由大到小 print(sorted(d.items(),key=itemgetter(0),reverse=True))#[('e', 10), ('c', 12), ('b', 1), ('a', 10)] # 值由大到小 print(sorted(d.items(),key=itemgetter(1),reverse=True))#[('c', 12), ('a', 10), ('e', 10), ('b', 1)]
prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75 } # 在一个字典上执行普通的数学运算,你会发现它们仅仅作用于键,而不是值 min(prices) # Returns 'AAPL' max(prices) # Returns 'IBM' min(prices.values()) # Returns 10.75 max(prices.values()) # Returns 612.78 min(prices, key=lambda k: prices[k]) # Returns 'FB' max(prices, key=lambda k: prices[k]) # Returns 'AAPL' min_price = min(zip(prices.values(), prices.keys())) # min_price is (10.75, 'FB') print("min_price",min_price) max_price = max(zip(prices.values(), prices.keys())) # max_price is (612.78, 'AAPL') print("max_price",max_price) #值由大到小排序 prices_sorted = sorted(zip(prices.values(), prices.keys()),reverse=True) # prices_sorted is [(10.75, 'FB'), (37.2, 'HPQ'), # (45.23, 'ACME'), (205.55, 'IBM'), # (612.78, 'AAPL')] print(prices_sorted)