Sort the dictionaries in Python __python

Source: Internet
Author: User

1, Key sorting

Method 1: The simplest way to arrange the elements (Key/value pairs) and then pick out the values. The items method of the dictionary returns a list of tuples in which each tuple contains a pair of items-the key and the corresponding value. The sort () method can be sorted at this time. def sortedDictValues1 (adict):
Items = Adict.items ()
Items.Sort ()
return [Value for key, value in items]

Method 2: Use the permutation key (key) way, pick out the value, speed is faster than Method 1. The Dictionary object's keys () method returns a list of all the key values in the dictionary, in a random order. You need to sort by using the sort () method on the returned list of key values. def sortedDictValues1 (adict):
Keys = Adict.keys ()
Keys.sort ()
return [Adict[key] for key in keys]

Method 3: Through the mapping method to more effectively perform the last step def sortedDictValues1 (adict):
Keys = Adict.keys ()
Keys.sort ()
return Map (Adict.get,keys)

Method 4: Sort the dictionary keys, return them in the form of a tuple list, and use a lambda function.

Sorted (iterable[, cmp[, key[, reverse]]]

CMP and key generally use lambda

Such as:
>>> d={"OK": 1, "No": 2}
Sort the dictionary keys and return them in the form of a tuple list
>>> Sorted (D.items (), Key=lambda d:d[0])
[(' No ', 2), (' OK ', 1)]

2, sorted by value

Sort the dictionary by value and return it in the form of a tuple list

Sorted (Dict.items (), Key=lambda d:d[1],reverse=true)

[(' OK ', 1), (' No ', 2)]

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.