To sort a dictionary by the value of a dictionary

Source: Internet
Author: User

Sometimes there is a need to sort the dictionary values by the value of the dictionary:

Here are two ways

#!/usr/bin/env python#coding:utf-8# @Author: Andyfrom random import randint# generate a random Dictdict1 = {X:randint (1, 10 0) for x in "Abczyx"}print (dict1) #method # Use built in function  sorted, Zipdict2 = sorted (Zip (dict1.values (), Dict1. Keys ())) print (DICT2) print ("*********") #method 2dict3 = sorted (Dict1.items (), key = Lambda x:x[1]) print (DICT3)

The above two methods end up sorting through a tuple, not a dictionary, which you can revert to a dictionary if you want.

Moreover, the form of tuples derived from the two methods is reversed. But if you need to get the key at this point, then both of these methods are very convenient.

To sort a dictionary by the value of a dictionary

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.