Python list and dictionary (by key, sorted by value) __python

Source: Internet
Author: User
Tags python list
python dict sorted by key:

1, Method 1.

Items = dict. Items () Items.Sort () for Key,value in Items:print key, value # print Key,dict[key]

2, Method 2.

Print key, Dict [key] for key ' in sorted (Dict. Keys ())

  python dict sorted by value:

Method 1:

Separate the elements in the dictionary into a list and sort the list to indirectly sort the dictionary. This "element" can be Key,value or item.

METHOD2:

#用lambda表达式来排序, more flexible: sorted (dict. Items (), Lambda X, y:cmp (x[1], y[1]) #降序 sorted (dict. Items (), Lambda X, y:cm P (x[1], y[1]), reverse = True)

The following is a help document for the Python built-in sorted function:

Sorted (...)
Sorted (iterable, Cmp=none, Key=none, Reverse=false)--> new sorted list python list sort:

The list has a sort method:

Such as:
>>> s=[2,1,3,0]
>>> S.sort ()
[0, 1, 2, 3]

Related Article

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.