Home > front end >  i want to sort all dictionary in increasing but whenever i get same values sort them in decreasing o
i want to sort all dictionary in increasing but whenever i get same values sort them in decreasing o

Time:05-04

 dic=dict(sorted(dic.items(),key=lambda x:x[1]))
 print(dic)

input={-1: 1, 5: 1, -6: 2, 4: 2, 1: 3}

desired_output={5:1, -1:1, 4:2, -6:2, 1:3}

can anyone suggest me some efficient way to do this

CodePudding user response:

We can concatenate the 2 values in the lambda, multiply the 2nd value by -1 so as to inverse the sort order.

dic={-1: 1, 5: 1, -6: 2, 4: 2, 1: 3}

dic=dict(sorted(dic.items(),key=lambda x:str(x[1]) str(-1*x[0])))
print(dic)

output

{5: 1, -1: 1, 4: 2, -6: 2, 1: 3}

CodePudding user response:

You can sort by tuple, so just change the key argument to this:

dic=dict(sorted(dic.items(), key=lambda x:(x[1], -x[0])))
  • Related