How to sort the Dict type key (keys) (Python 2.4 or later):
Mydict = {'Carl': 40, 'Alan': 2, 'Bob': 1, 'Danny': 3} forKeyinchSorted (Mydict.iterkeys ()):Print "%s:%s"% (key, Mydict[key])
Results:
Alan:213
Excerpt from Python faq:http://www.python.org/doc/faq/general/#why-doesn-t-list-sort-return-the-sorted-list.
If you sort by key (keys) in the reverse order, you need to add the reverse=true parameter to the sorted function.
How to sort the Dict type key (keys) (older than Python 2.4):
Keylist = Mydict.keys () keylist.sort () for in keylist: print" %s:%s" % (key, Mydict[key])
This procedure results in the same result as above.
How to sort by value (values) for the Dict type (Python 2.4 or later):
for in Sorted (Mydict.iteritems (), key=Lambda (k,v): (v,k)): print" %s:%s " % (key, value)
Results:
Bob:12340
Excerpt from Nick Galbreath's Digital Sanitation Engineering Blog article
See:
- The documentation for with
sorted
2.1 built-in Functions and the .sort()
method in 3.6.4 Mutable Sequence typesin the Python Li Brary Reference.
- Sorting dictionaries by Value in Python (improved.) by Gregg Lind August 30, 2008
Original URL:http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/
How to sort the Python dict type key (keys) or value (values)