Given the dictionary ab = {'b':2,'a':3,'c':1}, sort it by values to obtain {'c':1,'b':2,'a':3} and by keys to obtain {'a':3,'b':2,'c':1}.
💡 Model Answer
Use the built‑in sorted function with a custom key. For value‑based sorting, sort by the dictionary's values; for key‑based sorting, sort by the keys. Example:
# Sort by values
sorted_by_value = {k: v for k, v in sorted(ab.items(), key=lambda item: item[1])}
# Sort by keys
sorted_by_key = {k: v for k, v in sorted(ab.items(), key=lambda item: item[0])}
print(sorted_by_value) # {'c': 1, 'b': 2, 'a': 3}
print(sorted_by_key) # {'a': 3, 'b': 2, 'c': 1}
The sorted function runs in O(n log n) time and uses O(n) additional space for the new dictionaries.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500