Showcasing Olympic Champs: Rank & Shine!

Implementing Sorting and Ranking: Displaying the Top Performers on the Olympics Leaderboard

Welcome back, CodeCrafters! 🚀

In our last post, we learn about the basics of reading and writing data for our Olympics leaderboard.

Now, it’s time to take things up a notch by implementing sorting and ranking.

This will allow us to dynamically display the top performers based on different criteria, giving our leaderboard a more interactive and insightful edge.

 

Step 1: Sorting the Data

The first thing we need to do is sort our data. For this example, let’s assume our leaderboard data includes the following fields: country, athlete_name, gold_medals, silver_medals, bronze_medals, and total_medals. We’ll start by sorting the data based on total_medals.

 

Here’s a simple Python example using a list of dictionaries:

 

# Sample leaderboard data

leaderboard = [

    {"country": "USA", "athlete_name": "Athlete A", "gold_medals": 5, "silver_medals": 2, "bronze_medals": 1, "total_medals": 8},

    {"country": "China", "athlete_name": "Athlete B", "gold_medals": 4, "silver_medals": 3, "bronze_medals": 2, "total_medals": 9},

    {"country": "UK", "athlete_name": "Athlete C", "gold_medals": 3, "silver_medals": 2, "bronze_medals": 3, "total_medals": 8},

]

 

# Sorting by total medals in descending order

sorted_leaderboard = sorted(leaderboard, key=lambda x: x["total_medals"], reverse=True)

 

# Displaying the sorted leaderboard

for entry in sorted_leaderboard:

    print(f"{entry['athlete_name']} from {entry['country']} - Total Medals: {entry['total_medals']}")

In this snippet, we used Python’s sorted() function to sort our leaderboard by the total_medals field in descending order. This will give us a leaderboard that prioritizes those with the highest medal count.

Sorted according to Total Medals

Step 2: Ranking the Performers

Once we’ve sorted our data, the next step is to assign ranks to the performers. This can be easily achieved by iterating over the sorted list and assigning a rank based on the index.

 

# Assigning ranks

for index, entry in enumerate(sorted_leaderboard, start=1):

    entry["rank"] = index

 

# Displaying the ranked leaderboard

for entry in sorted_leaderboard:

    print(f"Rank {entry['rank']}: {entry['athlete_name']} from {entry['country']} - Total Medals: {entry['total_medals']}")

 

This code snippet assigns a rank to each entry based on their position in the sorted list. The highest-ranking performer will be at the top, followed by others in descending order.

Assigning Ranks in Descending Order

Step 3: Displaying the Top Performers

Now that we’ve ranked our athletes, let’s focus on displaying only the top performers. For this example, we’ll limit the display to the top 5 athletes.

 

# Displaying the top 5 performers

top_performers = sorted_leaderboard[:5]

 

print("Top 5 Performers:")

for entry in top_performers:

    print(f"Rank {entry['rank']}: {entry['athlete_name']} from {entry['country']} - Total Medals: {entry['total_medals']}")

 

This snippet slices the first five entries from the sorted leaderboard and displays them as the top performers. This is especially useful for highlighting the best of the best.

Top Performers

Step 4: Adding Interactivity

To make our leaderboard even more dynamic, we can allow users to choose different criteria for sorting. For instance, users might want to sort by gold_medals instead of total_medals.

 

# Function to sort by different criteria

def sort_leaderboard(leaderboard, sort_by="total_medals"):

    return sorted(leaderboard, key=lambda x: x[sort_by], reverse=True)

 

# Example: Sorting by gold medals

sorted_by_gold = sort_leaderboard(leaderboard, "gold_medals")

 

# Displaying the sorted list

for entry in sorted_by_gold:

    print(f"{entry['athlete_name']} from {entry['country']} - Gold Medals: {entry['gold_medals']}")

 

This function allows us to sort the leaderboard by any field we choose, making the leaderboard more flexible and user-friendly.

Sorting by Gold Medalists

How the sorted() woks

Now, let's break down how the sorted() function works with the line of code below:

 

sorted(leaderboard, key=lambda x: x["total_medals"], reverse=True)

 

Step 1: Understanding the sorted() Function

The sorted() function in Python is used to sort iterable objects like lists. It returns a new sorted list from the elements of any iterable (e.g., list, tuple, dictionary, etc.).

 

Syntax of sorted():

sorted(iterable, key=None, reverse=False)

  • iterable: The sequence (list, tuple, etc.) that you want to sort.

  • key: A function that serves as a basis for sorting. It extracts a comparison key from each element.

  • reverse: If True, the sorted list is returned in descending order. By default, it is False, which sorts in ascending order.

 

Step 2: Applying the key Parameter with a Lambda Function

In the example:

 

sorted(leaderboard, key=lambda x: x["total_medals"], reverse=True)

  • key=lambda x: x["total_medals"]: This part is critical.

  • lambda x: x["total_medals"] is a small anonymous (lambda) function.

  • It takes each element x in the leaderboard list, where x is a dictionary.

  • It returns the value associated with the "total_medals" key from each dictionary.

 

Example:

If x is {"country": "USA", "athlete_name": "Athlete A", "gold_medals": 5, "silver_medals": 2, "bronze_medals": 1, "total_medals": 8}, then lambda x: x["total_medals"] returns 8.

 

Step 3: Sorting Based on the Key 

Once the key function has been applied to each element, the sorted() function sorts the entire list based on these extracted values. In this case, it's sorting the list based on the "total_medals" value.

 

Step 4: The reverse=True Parameter

reverse=True:

This means the list will be sorted in descending order (from highest to lowest). If reverse=False (or omitted), the list would be sorted in ascending order.

 

Step 5: Final Output

The sorted() function returns a new list where the dictionaries (athletes in the leaderboard) are arranged in order of their "total_medals" values, with the athlete having the highest total medals appearing first.

 

Example Walkthrough

Given the following leaderboard:

 

leaderboard = [

    {"country": "USA", "athlete_name": "Athlete A", "gold_medals": 5, "silver_medals": 2, "bronze_medals": 1, "total_medals": 8},

    {"country": "China", "athlete_name": "Athlete B", "gold_medals": 4, "silver_medals": 3, "bronze_medals": 2, "total_medals": 9},

    {"country": "UK", "athlete_name": "Athlete C", "gold_medals": 3, "silver_medals": 2, "bronze_medals": 3, "total_medals": 8},

]

 

When you apply:

sorted_leaderboard = sorted(leaderboard, key=lambda x: x["total_medals"], reverse=True)

 

The sorted_leaderboard would be:

[

    {"country": "China", "athlete_name": "Athlete B", "gold_medals": 4, "silver_medals": 3, "bronze_medals": 2, "total_medals": 9},

    {"country": "USA", "athlete_name": "Athlete A", "gold_medals": 5, "silver_medals": 2, "bronze_medals": 1, "total_medals": 8},

    {"country": "UK", "athlete_name": "Athlete C", "gold_medals": 3, "silver_medals": 2, "bronze_medals": 3, "total_medals": 8},

]

 

In this result, the athletes are sorted in descending order based on their total_medals, with the one having the highest total at the top.

Wrapping Up 

By implementing sorting, ranking, and selective display, we’ve significantly enhanced the functionality of our Olympics leaderboard. Not only can we now easily identify the top performers, but we also give users the flexibility to view the data in the way that best suits their needs.

Coding with a Smile 🤣 😂

The 'None' Mystique:

Encountering 'None' in Python is like finding an empty box in the middle of a treasure hunt. It's not what you expected, but it’s a crucial clue nonetheless.

Let’s Inspire Future AI Coders Together! ☕

 

I’m excited to continue sharing my passion for Python programming and AI with you all. If you’ve enjoyed the content and found it helpful, do consider supporting my work with a small gift. Just click the link below to make a difference – it’s quick, easy, and every bit helps and motivates me to keep creating awesome contents for you.

Thank you for being amazing!

What’s Next? 📅

In the next post, we're going to dive deeper into our Olympics leaderboard project by exploring some exciting features! 🎯 

You'll learn how to filter the leaderboard by country or sport, making it even more powerful and user-friendly. Whether you want to see how a specific country is performing or check out the top athletes in a particular sport, these features will give your app a whole new level of functionality and refinement.

Get ready to take your leaderboard to the next level! 🥇📊

Ready for More Python Fun? 📬

Subscribe to our newsletter now and get a free Python cheat sheet! 📑 Dive deeper into Python programming with more exciting projects and tutorials designed just for beginners.

Keep learning, keep coding 👩‍💻👨‍💻, and keep discovering new possibilities! 💻

Enjoy your journey into artificial intelligence, machine learning, data analytics, data science and more with Python!

Stay tuned for our next exciting project in the following edition!

Happy coding!🚀📊✨

🎉 We want to hear from you! 🎉 How do you feel about our latest newsletter? Your feedback will help us make it even more awesome!

Login or Subscribe to participate in polls.