Maria
Maria

Reputation: 57

Sorting a JSON file for Discord leaderboards

looked around on StackOverflow, didn't find anything that answered my question. I attempted to do this by doing

async def leaderboard(self, ctx):
    leaderboard = {}
    with open("database.json") as f:
        leaderboard = json.load(f)
    f.close()
    sorted_data = {id: money for id, money in sorted(leaderboard.items(), reverse=True ,key=lambda money: money[1])}
    print(sorted_data)

I wanted to make a leaderboard for my Discord guild, and I have the currency of every user stored on a JSON file.

As an example, in the JSON file, they look like:

{
"_default": {

"30": {
    "money": 0,
    "userid": 349846310024642560
},
"32": {
    "money": 30861,
    "userid": 228718166602153985
},
"33": {
    "money": 325663,
    "userid": 180688669089202177
}
}
}

How can I sort this and grab the 10 or so richest users?

Upvotes: 1

Views: 151

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195438

You can use this example how to sort the dictionary by money key and then print top x users:

data = {
    "30": {"money": 0, "userid": 349846310024642560},
    "32": {"money": 30861, "userid": 228718166602153985},
    "33": {"money": 325663, "userid": 180688669089202177},
}

richest = sorted(data, key=lambda k: -data[k]["money"])

for k in richest[:2]:  # <-- change to 10 if you want top 10
    print(
        "Money: {:<10} UserId: {}".format(data[k]["money"], data[k]["userid"])
    )

Prints:

Money: 325663     UserId: 180688669089202177
Money: 30861      UserId: 228718166602153985

EDIT: With _default key:

data = {
    "_default": {
        "30": {"money": 0, "userid": 349846310024642560},
        "32": {"money": 30861, "userid": 228718166602153985},
        "33": {"money": 325663, "userid": 180688669089202177},
    }
}

data = data["_default"]
richest = sorted(data, key=lambda k: -data[k]["money"])

for k in richest[:2]:  # <-- change to 10 if you want top 10
    print(
        "Money: {:<10} UserId: {}".format(data[k]["money"], data[k]["userid"])
    )

Upvotes: 2

Related Questions