Klaus
Klaus

Reputation: 1731

Sorting a python dict by value length descending and then by key ascending

I am trying to solve this task where I have a dict having string keys and a string list of values.

I need to first sort the list by the length of the values in descending order and then for the tallies, I need to sort them in the ascending order or their keys.

My dict object looks like this {'XC': {'FF'}, 'AA': {'WW'}, 'XS': {'FF', 'DD'}} and I expect this to be sorted like {'XS': {'FF', 'DD'}, 'AA': {'WW'}, 'XC': {'FF'}}. In here, because the keys AA and XC both have a length of one in their values. Then, they should be ordered in the ascending order of the keys. Which yields to AA and then XC

I could get the first sorting done with this

sorted_keys = sorted( user_meals, key = lambda x: (len( user_meals[ x ] ), x), reverse = True )

print( key, user_meals[key] for key in sorted_keys ) # Because sorted returns a list in the prefered sorting order

Cannot figure out how to get sorting done on the keys in ascending order upon tallies of the value length.

Upvotes: 0

Views: 265

Answers (1)

Jiří Baum
Jiří Baum

Reputation: 6930

The missing piece is to use -len(...) to deal with the opposite sorting directions:

sorted( user_meals, key = lambda x: (-len( user_meals[ x ] ), x))

Upvotes: 2

Related Questions