Oscar Rénier
Oscar Rénier

Reputation: 95

How to sort a dictionary having string as keys and integer as values in Python

I'm trying to sort a dictionnary like:

dic = {"monday": 1, "tuesday": 1, "wednesday": 10, "thursday": 5, "friday": 10, "saturday": 11, "sunday": 11}

and I'm trying to have:

dic = {"saturday": 11, "sunday": 11, "friday": 10, "wednesday": 10, "thursday": 5, "monday": 1, "tuesday": 1}

So I tried this:

sortedPairs = sorted(dic.items(), key=lambda x: (x[1],x[0]), reverse=True)

and it seems to be working but for some reasons it never sorts the two lasts and I keep having this:

{"saturday": 11, "sunday": 11, "friday": 10, "wednesday": 10, "thursday": 5, "tuesday": 1, "monday": 1}

If someone could please help me out It'd be awesome!

Upvotes: 0

Views: 1423

Answers (2)

user6276743
user6276743

Reputation:

Close. You can try key=lambda x: (-x[1], x[0]) without reverse=True. What's important to note is that one element is being sorted in ascending order, while the other is being sorted in descending order (the latter takes priority in the tuple sort).

Upvotes: 1

DeepSpace
DeepSpace

Reputation: 81614

You need to flip the sort order on the day. Since you can't use - to compare strings, you should remove reverse=True and add -x[1].

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

which is now

[('saturday', 11), ('sunday', 11), ('friday', 10), ('wednesday', 10), ('thursday', 5),
 ('monday', 1), ('tuesday', 1)]

If you want a dict back use dict, but it will only be kept sorted on Python >= 3.7.

print(dict(sortedPairs))
# {'saturday': 11, 'sunday': 11, 'friday': 10, 'wednesday': 10, 'thursday': 5, 
#  'monday': 1, 'tuesday': 1}

Upvotes: 1

Related Questions