'Nextcord JSON File Parsing

I'm building a Discord Economy bot and am trying to create a leaderboard. But I cannot figure out how to get the combined values of the wallet, bank, and vault as well as the User ID linked to it. I've figured out how to sort by greatest net worth to least net worth, but I can't figure out how to get the User ID linked to those values as well. The User ID would preferably be a separate variable because I need to convert it to a username. Here is how my JSON file is currently structured.

{"theUserID": {"wallet": 0, "bank": 0, "vault": 0},"theUserID2": {"wallet": 0, "bank": 0, "vault": 0}}

If needed, here is my code for finding the greatest wallet amount.

        jsonFilePath = '/the/file/path'
    with open(jsonFilePath, 'r') as jsonFile:
        data = json.load(jsonFile)
        theList = []
        for key, value in data.items():
            wallet = value["wallet"]
            (theList.append(wallet))


    final_list = []
    for i in range(0, 5): 
        max1 = 0
      
        for j in range(len(theList)):     
            if theList[j] > max1:
                max1 = theList[j];
              
        theList.remove(max1);
        final_list.append(max1)

    print(final_list)


Solution 1:[1]

The simple way would be to create new list with objects having your data, then just compare the wallet values and sort

theList = list()

for val in data:
    theList.append(
        {
            'ID': val,
            'wallet': data[val]['wallet'],
        }
    )
        
i = 0

while (i <= len(theList)-2):

    if (theList[i]['wallet'] < theList[i+1]['wallet']):
        theList[i], theList[i+1] = theList[i+1], theList[i]
        if (i > 0):
            i -= 1
    else:
        i += 1

The sorting algorithm doesn't really matter if speed is not a problem. Of course you can add different fields later:

for val in data:
    theList.append(
        {
            'ID': val,
            'wallet': data[val]['wallet'],
            'bank': data[val]['bank'],
            'vault': data[val]['vault']
        }
    )

And then compute value for comparing the amount the way you want.

You'll access sorted data this way:

theList[0]['ID'] #gets the ID of a user with highest x value

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 marc_s