Python में Dictionary को Keys द्वारा Sort करना
Python के Standard Library में collections मॉड्यूल होता है जिसमें High-Performance Container Data Types की परिभाषाएं होती हैं। OrderedDict Dictionary का एक Subclass है जो Dictionary Object में Add की गई Entries के Order को याद रखता है। जब हम Ordered Dictionary पर Iterate करते हैं, तो Items उसी Order में Return होते हैं जिस Order में उनके Keys पहली बार Add किए गए थे।
उदाहरण: OrderedDict बनाना
>>> from collections import OrderedDict
>>> D = {5:'fff', 3:'ttt', 1:'ooo', 4:'bbb', 2:'ddd'}
>>> OrderedDict(D.items())
OrderedDict([(5, 'fff'), (3, 'ttt'), (1, 'ooo'), (4, 'bbb'), (2, 'ddd')])
हमें sorted() Function की भी आवश्यकता होती है जो किसी Iterable के Elements को Specified Order में Sort करता है। यह Function एक Function को Argument के रूप में लेता है जिसे Sorting के लिए Key के रूप में उपयोग किया जाता है। चूंकि हम Dictionary को Keys पर Sort करना चाहते हैं, इसलिए हम Tuple के 0th Element (Index 0) को Sorting के लिए Key के रूप में लेते हैं।
Keys द्वारा Sort करना
>>> D = {5:'fff', 3:'ttt', 1:'ooo', 4:'bbb', 2:'ddd'}
>>> OrderedDict(sorted(D.items(), key=lambda t: t[0]))
OrderedDict([(1, 'ooo'), (2, 'ddd'), (3, 'ttt'), (4, 'bbb'), (5, 'fff')])
OrderedDict Object को Regular Dictionary Object में Convert किया जा सकता है:
>>> D1 = dict(OrderedDict(sorted(D.items(), key=lambda t: t[0])))
>>> D1
{1: 'ooo', 2: 'ddd', 3: 'ttt', 4: 'bbb', 5: 'fff'}
नोट: Python 3.7+ में Regular Dictionaries भी Insertion Order को Maintain करते हैं, इसलिए OrderedDict का उपयोग अब कम आवश्यक है। आप सीधे dict(sorted(D.items(), key=lambda item: item[0])) का उपयोग कर सकते हैं।