Python: Sort Counter by value
35. Sort Counter by Value
Write a Python program to sort Counter by value.
Visual Presentation:

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)]
For more Practice: Solve these Related Problems:
- Write a Python program to sort a dictionary (or Counter) by its values in descending order and output a list of tuples.
- Write a Python program to use sorted() with a lambda function to arrange the items of a Counter based on frequency.
- Write a Python program to implement a function that takes a Counter object and returns its items sorted by value.
- Write a Python program to compare sorting a Counter by keys versus sorting by values and display the differences.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics