0

This is an extension on my previous question which was suitably answered, seen here: Sorting dictionary keys by value, then those with the same value alphabetically

I have a setup of users and scores in a dictionary, such that the key is "group.name" and the value is their score (e.g. "'3.Julie':'7' is a user "Julie" in group 3 with a score of 7). I already know how to sort it by value, and then by key:

sorted(dictionary.items(), key=lambda t: t[::-1])

but when it compares two keys, I want it to ignore the first character/two characters, so that users with the same score will be sorted alphabetically (whereas currently, they'd be sorted by group, as the group number comes first). Without changing the naming convention, is there anyway I can achieve this? (Ideally within the lambda key, a few lines is fine but if there's more than 2-3 it's not worth it)

Community
  • 1
  • 1
CharlieDeBeadle
  • 129
  • 1
  • 1
  • 9

1 Answers1

3

When you iterate over dict.items(), you get tuples (key, value), e.g.

>>> for t in {'3.Julie': '7'}.items():
       print t
('3.Julie', '7')

Currently, you're just reversing the whole thing:

>>> ('3.Julie', '7')[::-1]
('7', '3.Julie')

But you could be more explicit about what you want (i.e. second part, then first part), and include the slice to remove the relevant characters:

>>> t = ('3.Julie', '7')
>>> t[1], t[0][2:]
('7', 'Julie')

Therefore your sort becomes:

sorted(dictionary.items(), key=lambda t: (t[1], t[0][2:]))

Note that the parentheses in the lambda are necessary to indicate the tuple, otherwise t[0][2:] is interpreted as a positional argument to sorted.


If you want the value and the key to sort in opposite directions, you could do something like:

key=lambda t: (-int(t[1]), t[0][2:])

For example:

>>> d = {'1.John': '3', '2.Karl': '7', '3.Julie': '7'}
>>> sorted(d.items(), key=lambda t: (-int(t[1]), t[0][2:]))
[('3.Julie', '7'), ('2.Karl', '7'), ('1.John', '3')]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437