0

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.

yejin
  • 1
  • 2
  • Can you paste the first few lines from your CSV file so your code can be reproduced? Please also fix the indentation – FlyingTeller Jun 14 '22 at 14:34
  • Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – 001 Jun 14 '22 at 14:39

3 Answers3

0

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})]
Tom B.
  • 158
  • 9
0

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")
0

I try to simulate your data,

I think this works 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()



###output##############

#    =========================================
#    LEADERBOARD
#   Hossein - 75 - iambin
#    Joshua - 50 - djehfg
#    Patricia - 25 - fkri