How to sort the Python dict type key (keys) or value (values)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.