2

I have dictionary and I want to sort frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

I wanted to use cmp function but apparently this function is deprecated in python 3.

This is what I've done:

    dic = {'i': 2, 'like': 2, 'so': 1, 'coding': 1}
    output = [key for key, value in sorted(
        dic.items(), key=itemgetter(1, 0), reverse=True)]

    print(output) // ['like', 'i', 'so', 'coding']

My desired output is ['i, 'like', 'coding', 'so' ]

2 Answers 2

4

You can put - sign to first element in the sorting key to reverse the order:

dic = {'i': 2, 'like': 2, 'so': 1, 'coding': 1}

print([k for k, _ in sorted(dic.items(), key=lambda k: (-k[1], k[0]))])

Prints:

['i', 'like', 'coding', 'so']
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you it's working. Just one more question please what if I want to sort descending alphabetically
Do you mean sort depending on alphabet when both have same size? I didn't understand the question clearly.
@Melchia If you want to sort from highest frequency and descending alphabetically, then you can do sorted(dic.items(), key=lambda k: (k[1], k[0]), reverse=True), the output would be ['like', 'i', 'so', 'coding']
2

You can use key parameter in sorted. It will sort by value which is represented by x[1] else choose smallest size which is represented by -len(x[0])

output = [key for key,_ in sorted(dic.items(),key=lambda x: (x[1],-len(x[0])),reverse=True)]

Output:

['i', 'like', 'so', 'coding']

2 Comments

Actually it's alphabetically but Thanks I see how using the lambda is more powerful than itemgetter
Yes, in sort function you can provide a full function as key which is quite useful in a lot of cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.