Leroy Sharp
Leroy Sharp

Reputation: 65

How to sort index of dictionary in python

I have a method that sorts team values in an index starting from 1 and incrementing. It looks like this:

def create_ranking():
    sort_one = sorted(team_scores.items(), key=itemgetter(0))
    teams_sorted = sorted(sort_one, key=itemgetter(1), reverse=True)
    for idx, (team, score) in enumerate(teams_sorted, 1):
        suffix = 'pt' if score ==1 else 'pts'
        print(f'{idx}. {team + ","} {score} {suffix}')

It is currently giving me this output:

1. Tarantulas, 6 pts
2. Lions, 5 pts
3. FC Awesome, 1 pt
4. Snakes, 1 pt
5. Grouches, 0 pts

Currently it is sorting the dictionary according to score value and if scores are the same, it sorts it alphabetically.

How do I sort the dictionary if I need to display teams that have the same point score on the same index value. For example:

1. Tarantulas, 6 pts
2. Lions, 5 pts
*3. FC Awesome, 1 pt
3. Snakes, 1 pt*
4. Grouches, 0 pts

Upvotes: 1

Views: 98

Answers (2)

Duncan
Duncan

Reputation: 95652

Use itertools.groupby to collect together teams with the same score, then iterate through each group:

from operator import itemgetter
import itertools

sort_one = [
    ('Tarantulas', 6),
    ('Lions', 5),
    ('FC Awesome', 1),
    ('Snakes', 1),
    ('Grouches', 0),
]
teams_sorted = sorted(sort_one, key=itemgetter(1), reverse=True)
for idx, (score, group) in enumerate(itertools.groupby(teams_sorted, itemgetter(1)), 1):
    for team, ignore_score  in group:
        suffix = 'pt' if score ==1 else 'pts'
        print('{idx}. {team}, {score} {suffix}'.format(idx=idx, team=team, score=score, suffix=suffix))

Upvotes: 3

Brad Solomon
Brad Solomon

Reputation: 40878

As an alternative to itertools.groupby(), you can only increment the position-counter if the current score is not equal to the last-seen score:

>>> from operator import itemgetter
... 
>>> team_scores = {
...     'Tarantulas': 6,
...     'Lions': 5,
...     'FC Awesome': 1,
...     'Snakes': 1,
...     'Grouches': 0
... }
... 
>>> i, last = 0, -1
>>> for k, v in sorted(team_scores.items(), key=itemgetter(1), reverse=True):
...     if v != last:
...         i += 1
...     last = v
...     pts = 'pt' if v == 1 else 'pts'
...     print(f'{i}. {k + ","} {v} {pts}')
...     
1. Tarantulas, 6 pts
2. Lions, 5 pts
3. FC Awesome, 1 pt
3. Snakes, 1 pt
4. Grouches, 0 pts

Upvotes: 1

Related Questions