🎓 A1Learner
🔍
0 of 52 lessons completed

Python Project: A Leaderboard

A leaderboard ranks players by wins. Counting finds the wins, and sorting with a key sets the rank.

Count the wins

Each result adds one win for its player. Ada ends with 3 wins, and Bob ends with 2.

results = ["ada", "bob", "ada", "ada", "bob"]
wins = {}
for name in results:
    wins[name] = wins.get(name, 0) + 1
print(wins)

Rank by wins

sorted() with key=wins.get ranks the names by wins. reverse=True puts the most wins first.

wins = {"ada": 3, "bob": 2, "cy": 1}
ranked = sorted(wins, key=wins.get, reverse=True)
print(ranked)

Number the places

enumerate() counts the places from 1. Each name prints beside its place.

ranked = ["ada", "bob", "cy"]
for place, name in enumerate(ranked, start=1):
    print(place, name)

Example

results = ["ada", "bob", "ada", "cy", "bob", "ada", "dee", "bob", "ada", "cy"]
wins = {}
for name in results:
    wins[name] = wins.get(name, 0) + 1
ranked = sorted(wins, key=wins.get, reverse=True)
for place, name in enumerate(ranked, start=1):
    print(place, name, wins[name])
print("Games:", len(results))
print("Players:", len(wins))

Key points

  • Leaderboard: players ranked by wins, best first
  • Use dict.get() to count one win per player
  • Use sorted() with a key to rank the players by wins
  • Use reverse=True to put the most wins first
  • Use enumerate() to number the places from 1
  • A tie keeps the order the players first appeared in
  • The ranked list holds the player names in rank order.

In this example, the list holds ten game results for four players. The loop counts the wins for each player with get(). sorted() with key=wins.get ranks the names, most wins first. The printout shows Ada first with 4 wins, then Bob with 3, Cy with 2, and Dee with 1. The games total of 10 proves every result was counted.

Note

This project joins two tools from this course: counting with dicts and sorting with a key.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which key ranks the players by their wins?