w3resource

Python: Sort Counter by value

Python dictionary: Exercise-35 with Solution

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/dictionary/python-data-type-dictionary-exercise-35.php