16th Jan 2020, 3:57 AM
shreyash joshi
shreyash joshi - avatar
2 Answers
+ 5
If you sort in python, you have the ability to use the 'key' parameter. You can set key to a lambda function. lambda contains x:x[1] which tells the sorting how to calculate order of the dict elements. x[1] is the second part of a dict element, so it's the value. Sorting is done in this case according to the value in the dict. If you would use x:x[0], sorting will be done on the keys.
16th Jan 2020, 6:27 AM
Lothar
Lothar - avatar
+ 4
shreyash joshi mlist = [(7,8,9),(1,2,3), (10, 11, 12),( 3,8,5)] print(sorted(mlist, key=lambda x: x[1])) """" The key argument makes that a little more specific by saying, for each element (x) in mylist, return index 1 of that element, then sort all of the elements of the original list 'mylist' by the sorted order of the list calculated by the lambda function. Since we have a list of tuples, we can return an indexed element from that tuple. So we get: [(1,2,3),(7,8,9), (3, 8, 5),( 10,11,12)] """ Same in this way your code for dictionary is started and sorted the dictionary with the key values which is defined by you at x[1] index so every values are sorted according to that and return result in the form of ascending order of 1, 2, 3, 4 dictinory values
16th Jan 2020, 6:28 AM
DishaAhuja
DishaAhuja - avatar