![]() |
VOOZH | about |
This task becomes particularly useful when working with structured data, where tuples represent grouped information (e.g., names and scores, items and prices). Sorting such data enhances its readability and usability for further analysis.
For example, consider a dictionary d = {'student3': ('bhanu', 10), 'student2': ('uma', 12),'student4': ('sai', 11), 'student1': ('suma', 11)}, When sorted by keys, the dictionary will be {'student1': ('suma', 11), 'student2': ('uma', 12), 'student3': ('bhanu', 10), 'student4': ('sai', 11)}. When sorted by the name, the output will be {'student3': ('bhanu', 10), 'student4': ('sai', 11), 'student1': ('suma', 11), 'student2': ('uma', 12)}. When sorted by the score, the dictionary will be {'student3': ('bhanu', 10), 'student4': ('sai', 11), 'student1': ('suma', 11), 'student2': ('uma', 12)}.
OrderedDict from the collections module allows us to sort a dictionary while preserving its insertion order. It’s useful when we need the result as an ordered dictionary.
OrderedDict({'bhanu': 10, 'sai': 11, 'suma': 11, 'uma': 12})
OrderedDict({'student1': ('suma', 11), 'student2': ('uma', 12), 'student3': ('bhanu', 10), 'student4': ('sai', 11)})
Explanation:
This method converts the result of the sorted() function into a standard dictionary. It is straightforward and suitable for small datasets where efficiency is less critical.
('student1', ('bhanu', 10)) ('student2', ('ravi', 11)) ('student3', ('suma', 11)) ('student4', ('uma', 12)) ('student5', ('gayatri', 9)) ('gayatri', 9) ('bhanu', 10) ('suma', 11) ('ravi', 11) ('uma', ...Explanation:
When working with dictionaries of tuples, sorting by tuple elements using heapq is particularly advantageous for large datasets, as it reduces computational overhead compared to full in-memory sorting.
[('student3', ('bhanu', 10)), ('student4', ('sai', 11)), ('student1', ('suma', 11)), ('student2', ('uma', 12))]
[('student2', ('uma', 12)), ('student1', ('suma', 11)), ('student4', ('sai', 11)), ('stu...Explanation: