程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python dictionary sorting

編輯:Python

according to key Sort

Call directly sorted(iterable,key,reverse)
1. Output key only :

>>> test_dict = {
'a':1, 's':5, 'd':2, 'f':3}
>>> sorted(test_dict.keys())
['a', 'd', 'f', 's']

2. Key values are output at the same time

>>> sorted(test_dict.items(), key=lambda item:item[0])
[('a', 1), ('d', 2), ('f', 3), ('s', 5)]

according to value Sort

Method 1 :sorted Methodical key Parameters use lambda obtain value Value to sort

>>> sorted(test_dict.items(), key=lambda item:item[1])
[('a', 1), ('d', 2), ('f', 3), ('s', 5)]
>>> sorted(test_dict.items(), key=lambda item:item[1], reverse = True)
[('s', 5), ('f', 3), ('d', 2), ('a', 1)]

Method 2 : Use operator Of itemgetter Sort
itemgetter Function is used to get the data of which location of the object , The parameter is the sequence number value representing the position .

>>> import operator
>>> sorted(test_dict.items(), key=operator.itemgetter(1))
[('a', 1), ('d', 2), ('f', 3), ('s', 5)]
>>> sorted(test_dict.items(), key=operator.itemgetter(1), reverse = True)
[('s', 5), ('f', 3), ('d', 2), ('a', 1)]

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved