Home > OS >  how can I sort the data based on the scores?
how can I sort the data based on the scores?

Time:06-15

How can I sort the player data based on the scores without using import Panda?

Here's my code:

player = {}
playerData = {}

def loadData():
    fileHandle = open('Leaderboard.csv', 'r')
    player.clear()
    for line in fileHandle:
        data = line[0:-1].split(",")
        playerName = data[0]
        playerScore = data[1]
        playerPattern = data[2]
        playerData = {}
        playerData["Score"] = playerScore
        playerData["Pattern"] = playerPattern
        player[playerName] = playerData
    fileHandle.close()

def leaderboard():
    print("=========================================")
    print("LEADERBOARD")
    for k in player:
        playerData = player[k]
        playerScore = playerData["Score"]
        playerPattern = playerData["Pattern"]
        print(k   " - "   playerScore   " - "   playerPattern)
    print("\n")

This is my CSV sample:

Liam      10    kdi
Joshua    50    djehfge
Patricia  25    fkris

I want my output to be like this:

Joshua - 50 - djehfge
Patricia - 25 - fkris
Liam - 10 - kdi

Don't mind the pattern, I just want to sort it based on the scores. Your help would be appreciated.

CodePudding user response:

You can use the built in sorted function.

Example using test data as we do not know what yours looks like:

player = {"player1": {"name": "player1", "Score": 10},
          "player2": {"name": "player2", "Score": 20},
          "player3": {"name": "player3", "Score": 5}}
leaderboard = sorted(player.items(), key=lambda x: x[1]['Score'], reverse=True)
print(leaderboard)

Output:

[('player2', {'name': 'player2', 'score': 20}),
 ('player1', {'name': 'player1', 'score': 10}),
 ('player3', {'name': 'player3', 'score': 5})]

CodePudding user response:

You can use list of tuples instead dict, and sort them by column index (started from zero).

rows = []
with open("Leaderboard.csv", mode="r") as f:
    for line in f.readlines():
        rows.append(line.split(","))

print("=" * 50)
print("LEADERBOARD")
for player, score, pattern in sorted(rows, key=lambda row: row[1], reverse=True):
    print(f"{player} - {score} - {pattern}")
print("\n")

CodePudding user response:

I try to simulate your data,

I think this work for you:

from collections import OrderedDict

player = {}
playerData = {}

sampledata=[
    "Joshua,50,djehfge",
    "Patricia,25,fkris",
    "Hossein,75,iambini"
]
index_sort_key="Score"
def loadData():
    player.clear()
    for line in sampledata:
        data = line[0:-1].split(",")
        playerName = data[0]
        playerScore = data[1]
        playerPattern = data[2]
        playerData = {}
        playerData["Score"] = playerScore
        playerData["Pattern"] = playerPattern
        player[playerName] = playerData
def leaderboard():

    print("=========================================")
    print("LEADERBOARD")
    for k in player:
        playerData = player[k]
        playerScore = playerData["Score"]
        playerPattern = playerData["Pattern"]
        print(k   " - "   playerScore   " - "   playerPattern)

loadData()

player = OrderedDict(sorted(player.items(), key=lambda value:value[1][index_sort_key],reverse=True))

leaderboard()
  • Related