Home > Mobile >  sorting dictionary in python by value where the keys are tuple
sorting dictionary in python by value where the keys are tuple

Time:06-30

how can I sort a dictionary in python by its value where the key is a tuple and after sorting based on value, how can I get back the corresponding key? I have a dictionary like: { (1,1) : 25 , (1,2) : 36 , (1,3) :21 ,(2,1):45 ,(2,2): 87, (2,3) : 70}. I want to sort based on the values . The output should be : {(1,3):21 , (1,1):25 , (1,2):36 , (2,1):45 , (2,3):70, (2,2):87}

CodePudding user response:

You can sort a dictionary by its value like this:

some_dict = {(1,1): 25, (1,2): 36, (1,3): 21, (2,1): 45, (2,2): 87, (2,3): 70}

sorted_dict = dict(sorted(some_dict.items(), key=lambda x:x[-1]))

print(sorted_dict)

Output: {(1, 3): 21, (1, 1): 25, (1, 2): 36, (2, 1): 45, (2, 3): 70, (2, 2): 87}


You can then get the keys in order using

print(list(sorted_dict.keys()))

Output: [(1, 3), (1, 1), (1, 2), (2, 1), (2, 3), (2, 2)]

  • Related