SoFunction
Updated on 2024-10-30

How Python sorts by values in a dictionary

How to sort the items in a dictionary according to the size of the values in the dictionary

practical example

The English grades for a class are stored in dictionary form as {'LiLei': 79, 'Jim': 88, 'Lucy': 92, ...}

Student rankings are calculated based on high and low grades.

Note: The key of the dictionary is the student's name and the value of the dictionary is the student's score.

prescription

Using the built-in function sorted

Method 1: Using zip to convert dictionary data into a list of tuples

Method 2: The key argument passed to the sorted function

Code Demo

# Sort the list using sorted
print(sorted([9, 1, 2, 8, 5]))
 
from random import randint
 
# Create a randomized table of grades, using dictionary parsing
c = {x: randint(60, 100) for x in 'abcded'}
print(c)
print(sorted(c))
# Method 1:
'''
Direct usesortedSorting the dictionary,It's not sorted by value,Instead, follow the key。
sorted()Passed in are iterable objects,Some kind of conversion for dictionaries,Let it be.sortedSortable structures。
Converting a dictionary to a list of tuples,as if: [(97, 'a'), (69, 'b')],Then directly compare the first value of the tuple
'''
# Get all the values of the dictionary, or all the values of the dictionary.
# print(())
# print(())
# Use the zip function, two lists will be put together into a list, because the return is an object so use the list () function to convert it
print(list(zip((), ())))
# Then sort the synthesized list of tuples #
print(sorted(zip((), ())))
 
# Method 2:
# Return the k:v of the dictionary as a list of tuples
print(())
# Set the key argument of sorted to the value of the dictionary
print(sorted((), key=lambda x: x[1]))

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.