Python implements the method of sorting dictionaries according to value

  • 2020-06-19 10:50:27
  • OfStack

This article illustrates the Python implementation of sorting dictionaries by value. To share for your reference, specific as follows:

Let me talk about a few solutions, but I'll talk more about them later


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

The dictionary is this, and then you have to sort the dictionary by value

Method 1:


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

Method 2:


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

Method 3:


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

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

PS: Here is another demo tool on sorting for your reference:

Online animation demonstration of insert/Select/Bubble/merge/Hill/Quicksort algorithm process tools:
http://tools.ofstack.com/aideddesign/paixu_ys

For more information about Python, please refer to: Python Data Structure and Algorithm Tutorial, Python Encryption and Decryption Algorithm and Skills Summary, Python Coding skills Summary, Python Function Use Skills Summary, Python String Manipulation Skills Summary and Python Introduction and Advanced Classic Tutorial.

I hope this article has been helpful in Python programming.


Related articles: