A Python
A Python

Reputation: 93

How to sort a list obtained in a dictionary by a specific value

I have a bit of code set up that grabs the .JSON file from all players that have one to their name, open that and pull out values, and place it all in a list to attach to a dictionary. The idea is to take that information, and to apply it in descending order and print it out. Rather than trying to show the .JSON files and all, I did my best to create an example script and run it to test around with. It is the following:

dictExample = {1:["Sam", "Player 1", 1, 3], 2:["Sue", "Player 2", 4 ,3],3:["Goerge", "Player 3", 3, 3],4:["Jorge", "Player 4", 0, 0]}

sorted()
num = input("number: ")

for num in range(1, 5):
    total = dictExample[num][2] + dictExample[num][3]
    try:
        percent = (dictExample[num][2] / total) * 100
    except ZeroDivisionError:
        percent = 0
    print(dictExample[num][1] + " (" + dictExample[num][0] + "): " + str(dictExample[num][2]) + "wins/" + str(dictExample[num][3]) + "losses. (" + strExample(percent) + "%)")

I would like it to arrange the dictionary in the following way: {1:["Sue", "Player 2", 4 ,3], 2:["Goerge", "Player 3", 3, 3], 3:["Sam", "Player 1", 1, 3], 1:["Jorge", "Player 4", 0, 0]} This way the dictionary can be ran through that for statement, and list them in descending order according to the value found in the second index.

I have tried looking around on the internet for options to help me with, but every example I find is always a 1 to 1 ratio. Meaning one key always has only one value Most common example is: {4:Four, 2:Two, 3:Three, 1:One}, and how to use the sort(), or sorted() functions to order them how you want.

Do I need to run a loop to place it all into one giant list inside a single list? Or is there a way to manipulate the data as is? Any help would be appreciated, thanks.

Upvotes: 0

Views: 50

Answers (1)

Pranav Void
Pranav Void

Reputation: 357

Is this what you want ??

>>> indices = sorted(dictExample, key=lambda d: dictExample[d][2], reverse=True)
>>> for i in indices:
        print(dictExample[i])

['Sue', 'Player 2', 4, 3]
['Goerge', 'Player 3', 3, 3]
['Sam', 'Player 1', 1, 3]
['Jorge', 'Player 4', 0, 0]

Upvotes: 1

Related Questions