w3resource

Python: Sort Counter by value


Write a Python program to sort Counter by value.

Visual Presentation:

Python Dictionary: Sort Counter by value.

Sample Solution:

Python Code:

# Import the 'Counter' class from the 'collections' module.
from collections import Counter

# Create a Counter object 'x' with subjects as keys and associated scores as values.
x = Counter({'Math': 81, 'Physics': 83, 'Chemistry': 87})

# Print the most common elements in the 'x' Counter, which are subject-score pairs.
print(x.most_common())

Sample Output:

[('Chemistry', 87), ('Physics', 83), ('Math', 81)]

Python Code Editor:

Previous: Write a Python program to count number of items in a dictionary value that is a list.
Next: Write a Python program to create a dictionary from two lists without losing duplicate values.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.