Sort a Python dictionary by value

Source: Internet
Author: User
Tags key string pear

The first thing to make clear is that Python's dict itself cannot be sorted and more explicitly expressed as "a list of dict through operations into value ordered"

There are several ways to do this:

1.

Import= {1:2, 3:4, 4:3, 2:1= sorted (X.items (), Key=operator.itemgetter (1))# sorted by Value  = sorted (X.items (), key=operator.itemgetter (0))#sorted by key

2.

Sorted (Dict1, Key=dict1.get)

3.

Sorted (D.items (), key=Lambda x:x[1])

4.

 for  in Mydict.items ()])

5. Use Ordereddict

>>>#regular unsorted dictionary>>> d = {'Banana': 3,'Apple': 4,'Pear': 1,'Orange': 2}>>>#dictionary sorted by key>>> ordereddict (Sorted (D.items (), key=Lambdat:t[0])) Ordereddict ([('Apple', 4), ('Banana', 3), ('Orange', 2), ('Pear', 1)])>>>#dictionary sorted by value>>> ordereddict (Sorted (D.items (), key=LambdaT:t[1]) ordereddict ([('Pear', 1), ('Orange', 2), ('Banana', 3), ('Apple', 4)])>>>#dictionary sorted by length of the key string>>> ordereddict (Sorted (D.items (), key=LambdaT:len (t[0])) Ordereddict ([('Pear', 1), ('Apple', 4), ('Orange', 2), ('Banana', 3)])

Sort a Python dictionary by value

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.