Python dictionary sort

Source: Internet
Author: User

We all know that dictionaries are unordered, how do we sort them according to the dictionary key or value?

Sort by key of the dictionary

Available in three ways:
1. Using lambda

>>> a = {‘b‘:‘a‘,‘d‘:‘d‘,‘a‘:‘a‘}>>> sorted(a.items(),key=lambda x:x[0])[(‘a‘, ‘a‘), (‘b‘, ‘a‘), (‘d‘, ‘d‘)]

2. Using operator module

>>> import operator>>> sorted(a.items(),key=operator.itemgetter(0))[(‘a‘, ‘a‘), (‘b‘, ‘a‘), (‘d‘, ‘d‘)]

3. Direct use of sorted
The dictionary key is sorted by default

>>> sorted(a.items())[(‘a‘, ‘a‘), (‘b‘, ‘a‘), (‘d‘, ‘d‘)]
Sort by value of dictionary

Available in two ways:
1, use lambda, change the index can be

>>> a = {‘a‘:‘d‘,‘b‘:‘a‘,‘c‘:‘b‘}>>> sorted(a.items(),key=lambda x:x[1])[(‘b‘, ‘a‘), (‘c‘, ‘b‘), (‘a‘, ‘d‘)]

2, the use of operator, but also change the index can be

>>> import operator>>> sorted(a.items(),key=operator.itemgetter(1))[(‘b‘, ‘a‘), (‘c‘, ‘b‘), (‘a‘, ‘d‘)]

It is important to note that sorted () does not change its value by default, just return a result

Just wrap it up with the Dict function:

>>> a = dict(sorted(a.items(),key=lambda x:x[0]))>>> a{‘a‘: ‘d‘, ‘b‘: ‘a‘, ‘c‘: ‘b‘}

Python dictionary sort

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.