Python is sorted according to the value of the dictionary:

Source: Internet
Author: User

There is a list of nested dictionaries: [{"a": 5}, {"B":4}, {"C": 1},{"e": 2}, {"D ": 3}], their values are not the same, now you want to sort by values:

< Span style= "COLOR: #800000" > < Span style= "COLOR: #800000" > idea: For a value sort, first take the value out of the dictionary, Place this value in a dictionary and a smaller position so that it can be sorted by value

< Span style= "COLOR: #800000" > < Span style= "COLOR: #800000" > Sorting by different keys is the same.

Specific code implementation

1 #define a method to remove a value from a dictionary2 defGet_val (_dict):3val =list (_dict.values ()) [0] # Sort by value: Change . VALUES () to. Keys () OK4     returnVal5 6 7 #Defining Collations8 defBoff_sort (_list):9n =Len (_list)Ten      forIinchRange (n-1): One          forJinchRange (n-1-i): A             ifGet_val (_list[j]) > Get_val (_list[j+1]):#to sort the values in the dictionary -_LIST[J], _list[j+1] = _list[j+1], _list[j] -  the  - if __name__=='__main__': -Li = [{"a": 5}, {"b": 4}, {"C": 1},{"e": 2}, {"D": 3}] - Boff_sort (LI) +     Print(LI) - #The run result is [{' C ': 1}, {' E ': 2}, {' d ': 3}, {' B ': 4}, {' A ': 5}]

When you sort the same key, it's easy to use a lambda function to get it done.

Python is sorted according to the value of the dictionary:

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.