2017年4月15日 星期六

[ Python 範例代碼 ] How to sort a Python dict (dictionary) by keys or values

來源自 這裡 
How-To 
- How to sort a dict by keys (Python 2.4 or greater): 
  1. mydict = {'carl':40,  
  2.           'alan':2,  
  3.           'bob':1,  
  4.           'danny':3}  
  5.   
  6. for key in sorted(mydict.iterkeys()):  
  7.     print "%s: %s" % (key, mydict[key])  
執行結果 
alan: 2
bob: 1
carl: 40
danny: 3

Taken from the Python FAQ: http://www.python.org/doc/faq/general/#why-doesn-t...t-sort-return-the-sorted-list. To sort the keys in reverse, add reverse=True as a keyword argument to the sorted function. 

- How to sort a dict by keys (Python older than 2.4): 
  1. keylist = mydict.keys()  
  2. keylist.sort()  
  3. for key in keylist:  
  4.     print "%s: %s" % (key, mydict[key])  
The results are the same as the above. 

- How to sort a dict by value (Python 2.4 or greater): 
  1. for key, value in sorted(mydict.iteritems(), key=lambda (k,v): (v,k)):  
  2.     print "%s: %s" % (key, value)  
Results: 
bob: 1
alan: 2
danny: 3
carl: 40

Taken from Nick Galbreath's Digital Sanitation Engineering blog article

- More Examples to sort dict by key/value 
>>> d = {'John':30, 'Allen':41, 'Ken':28, 'Mary':18}
>>> import operator
>>> sorted_d = sorted(d.items(), key=operator.itemgetter(1)) # Sorting dict items (key, value) by value
>>> sorted_d
[('Mary', 18), ('Ken', 28), ('John', 30), ('Allen', 41)]
>>> sorted(d.items(), key=operator.itemgetter(1), reverse=True) # Sorting dict items (key, value) by value in descending order
[('Allen', 41), ('John', 30), ('Ken', 28), ('Mary', 18)]
>>> sorted_d = sorted(d.items(), key=operator.itemgetter(0)) # Sorting dict items (key, value) by key
>>> sorted_d
[('Allen', 41), ('John', 30), ('Ken', 28), ('Mary', 18)]
>>> sorted(d.items(), key=operator.itemgetter(0), reverse=True)
[('Mary', 18), ('Ken', 28), ('John', 30), ('Allen', 41)]


Related posts: 
Python data object motivated by desire for a mutab...namedtuple with default values — posted 2012-08-03 
How to sort a list of dicts in Python — posted 2010-04-02 
Python setdefault example — posted 2010-02-09 
How to conditionally replace items in a list — posted 2008-08-22 
How to use Python's enumerate and zip to iterate o...er two lists and their indices. — posted 2008-04-18 
How to invert a dict in Python — posted 2008-01-14 
Sort a Python dictionary by value 

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...