how to sort a python dict according to its values?
- User
how to sort a python dict according to its values?
- Assistant
You can sort a Python dictionary by its values using the built-in sorted() function together with a lambda. Here are a few common ways:
✅ 1. Sort ascending by values pythonCopy codedata = {'apple': 3, 'banana': 1, 'cherry': 2}
sorted_data = dict(sorted(data.items(), key=lambda item: item[1])) print(sorted_data)
Output: bashCopy code{'banana': 1, 'cherry': 2, 'apple': 3}
✅ 2. Sort descending by values pythonCopy codesorted_data_desc = dict(sorted(data.items(), key=lambda item: item[1], reverse=True)) print(sorted_data_desc)
Output: bashCopy code{'apple': 3, 'cherry': 2, 'banana': 1}
✅ 3. Get a list of keys sorted by their values pythonCopy codesorted_keys = sorted(data, key=data.get) print(sorted_keys)
Output: cssCopy code['banana', 'cherry', 'apple']
Would you like the result to stay as a dict or as a list of (key, value) pairs?