English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Analysis of Sorting Dictionaries by Value in Python

This article describes a method to sort a dictionary in Python by value. Shared for everyone's reference, as follows:

First, let's talk about some solutions, and we will elaborate on them in detail when we have time.

d = {'a':1,'b':4,'c':2}

The dictionary is this, and then the dictionary needs to be sorted by value

Method One:

sorted(d.items(),key = lambda x:x[1],reverse = True)

Method Two:

import operator
sorted(d.items(),key = operator.itemgetter(1))

Method Three:

f = zip(d.values(),d.keys())
sorted(f)
//The result is [(1, 'a'), (2, 'c'), (4, 'b')]

After zipping, the zip function will sort the first element by default

PS: Here is another sorting demonstration tool recommended for everyone's reference:

Online Animation Demonstration Insertion/Selection/Bubble/Merge/Shell/Quick Sort Algorithm Process Tool:
http://tools.jb51.net/aideddesign/paixu_ys

Readers who are interested in more related content about Python can check the special topics on this site: 'Python Data Structures and Algorithms Tutorial', 'Python Encryption and Decryption Algorithms and Techniques Summary', 'Python Coding Operation Techniques Summary', 'Python Function Usage Techniques Summary', 'Python String Operation Techniques Summary', and 'Python Entry and Advanced Classic Tutorial'

I hope the content described in this article will be helpful to everyone in designing Python programs.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously, and this website does not own the copyright. It has not been edited by humans and does not assume any relevant legal responsibility. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (when sending an email, please replace # with @ to report, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like