2015-10-14 134 views
0

我在使用這個Python時遇到了一些麻煩。我試圖按字母順序對字典進行排序,從最小值到最大值(包含值)以及從最大值到最小值(按值)。我怎樣才能做到這一點?Python - 排序字典

注:我不能得到最大到最小工作

stocks = { 
    'GOOG': 520.24, 
    'FB': 331.28, 
    'XMZN': 89.72, 
    'APPL': 112.31 
} 

# for min to max 
print(sorted(zip(stocks.values(), stocks.keys()))) 

# for alphabetically 
print(sorted(zip(stocks.keys(), stocks.values()))) 

# for max to min 
print(sorted(zip(stocks.values(), stocks.keys(), reverse)) 
+1

可能的複製(http://stackoverflow.com/questions/4183506/python-list -order-in-descending-order) – The6thSense

回答

1

您可以使用反向[::-1]

# for max to min 
print(sorted(zip(stocks.values(), stocks.keys()))[::-1]) 

輸出列表:

[(520.24, 'GOOG'), (331.28, 'FB'), (112.31, 'APPL'), (89.72, 'XMZN')] 
4

關鍵字參數必須是給定一個值,否則該標識符將被用作名稱。

print(sorted(zip(stocks.values(), stocks.keys(), reverse=True)) 
+0

up vote,but possible duplicate of [this](http://stackoverflow.com/questions/4183506/python-list-sort-in-descending-order/4183540#4183540):p – The6thSense

2
stocks = { 
'GOOG': 520.24, 
'FB': 331.28, 
'XMZN': 89.72, 
'APPL': 112.31 
} 

print sorted(stocks.items(),key=lambda x:x[1],reverse=True) 

你可以簡單地做,而不是zip這一點,[按降序排列Python列表排序]的所有