जब कुंजी के 'i'वें इंडेक्स मान के आधार पर डिक्शनरी की सूची को क्रमबद्ध करना आवश्यक हो, तो 'sorted' विधि और लैम्ब्डा विधियों का उपयोग किया जाता है।
उदाहरण
नीचे इसका प्रदर्शन दिया गया है:
my_list = [{"Python": "Best", "to": "Code"}, {"Python": "Good", "to": "Learn"}, {"Python": "object", "to": "cool"}, {"Python": "oriented", "to": "language"}]
print("The list is : ")
print(my_list)
K = "Python"
print("The value of K is ")
print(K)
i = 2
print("The value of i is :")
print(i)
my_result = sorted(my_list, key = lambda sub: sub[K][i])
print("The resultant list is : ")
print(my_result)
आउटपुट
The list is : [{'Python': 'Best', 'to': 'Code'}, {'Python': 'Good', 'to': 'Learn'}, {'Python': 'object', 'to': 'cool'}, {'Python': 'oriented', 'to': 'language'}]
The value of K is Python
The value of i is : 2
The resultant list is : [{'Python': 'oriented', 'to': 'language'}, {'Python': 'object', 'to': 'cool'}, {'Python': 'Good', 'to': 'Learn'}, {'Python': 'Best', 'to': 'Code'}]
व्याख्या
डिक्शनरी की एक सूची बनाई गई है और कंसोल पर प्रदर्शित की गई है।
'K' का मान परिभाषित किया गया है और कंसोल पर प्रदर्शित किया गया है।
'i' का मान परिभाषित किया गया है और कंसोल पर प्रदर्शित किया गया है।
'sorted' विधि का उपयोग लैम्ब्डा फ़ंक्शन को कुंजी के रूप में उपयोग करके सूची को क्रमबद्ध करने के लिए किया जाता है।
इसे एक चर को निर्दिष्ट किया जाता है।
इस चर को कंसोल पर आउटपुट के रूप में प्रदर्शित किया जाता है।