Home > front end >  How to sort dictionary based on values and if multiple keys have same values then sort by keys
How to sort dictionary based on values and if multiple keys have same values then sort by keys

Time:12-03

a = [1,1,1,11,2,2,2,2,2,3,3,3,3,4,4,4,4,8,11,8,8,5,11,7,7,7,7,7,]

freq = dict()

for i in a :
    freq[i] = freq.get(i, 0)  1


fsort = dict(sorted(freq.items(), key=lambda item:item[1], reverse=True))
print(fsort)

The above code counts the frequencies of the numbers and returns a dictionary of frequencies, at this stage the dictionary is sorted based on the values. Now how can I sort keys having the same values in descending order? Here is the output and expected output of the code:

Output:
{2: 5, 7: 5, 3: 4, 4: 4, 1: 3, 11: 3, 8: 3, 5: 1}


Expected Output:
{7: 5, 2: 5, 4: 4, 3: 4, 11: 3, 1: 3, 8: 3, 5: 1}

CodePudding user response:

You can use a tuple as the key. Specifically a tuple of the form (value, key):

dict(sorted(freq.items(), key=lambda item: item[::-1], reverse=True))

CodePudding user response:

You can invert each key value pair and take the negative value of each (without setting reverse=True):

dict(sorted(freq.items(),key=lambda item:(-item[1],-item[0])))

This approach allows you to be more flexible in case you need to sort ascending for keys and descending for values (or vice versa). You just need to change the signs in the lambda function.

CodePudding user response:

For your dict, you can simply sort with key=lambda x: (x[1], x[0])

For your code, you can also use a Counter from collection module, like this:

freq = Counter(a)
  • Related