Sorting a Counter by Value

Write a Python function that takes a dictionary as input and returns a sorted dictionary based on the values in descending order.

Example 1:

Input: {"a": 2, "b": 1, "c": 3} 
Output: {"c": 3, "a": 2, "b": 1}

Example 2:

Input: {"x": 20, "y": 30, "z": 10} 
Output: {"y": 30, "x": 20, "z": 10}

Use the built-in sorted function in Python with a custom sorting key that sorts by the dictionary values.

def sort_counter(counter):
return {k: v for k, v in sorted(counter.items(), key=lambda item: item[1], reverse=True)}

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!