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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM