data = {'apple': 3, 'banana': 1, 'cherry': 2} write me python code to return a sorted…
- User
data = {'apple': 3, 'banana': 1, 'cherry': 2}
write me python code to return a sorted list based on the dict's values
- Assistant
You can do this using Python’s built-in sorted function with a key on the dictionary values. For example: pythonCopy codedata = {'apple': 3, 'banana': 1, 'cherry': 2}
Sort by values (ascending)
sorted_list = sorted(data.items(), key=lambda item: item[1])
print(sorted_list)
This will output: pythonCopy code[('banana', 1), ('cherry', 2), ('apple', 3)]
👉 If you just want the keys in sorted order by their values, you can do: pythonCopy codesorted_keys = sorted(data, key=data.get) print(sorted_keys)
Which gives: pythonCopy code['banana', 'cherry', 'apple']
Do you want the result as key-value pairs ([('banana', 1), ...]) or just the keys (['banana', 'cherry', 'apple'])?