Skip to content Skip to sidebar Skip to footer

Sorting A Dictionary By An Inner "attribute" Dictionary Key-value

I created a dictionary using a for-loop and this code: players[name] = {'roll_total': player_roll, 'ante': None} Previously my dictionary was just players = {names: totals} and I

Solution 1:

That happens because you are comparing two dictionaries.Use:

players = [(k, players[k]) for k in sorted(players, key=lambda x: players[x]['roll_total'], reverse=True)]

The lambda function receives the key of name as x and then sorts on the basis of players[x]['roll_total'] which is basically players[name]['roll_total'].

Solution 2:

You can also make this a dictionary comprehension and then assign it to the variable name of the dictionary on which you're iterating. That way, you're retaining the dictionary and can change it at certain logical junctures, making it available in later program flow as sorted. For instance, maybe you want the winner to start the next round, or something like that, and instead of making a new dictionary from the list, you already have the dictionary at hand, in only one operation:

{k: players[k] for k in sorted(players, key=lambda x: players[x]['rolltotal'], reverse=True)}

Post a Comment for "Sorting A Dictionary By An Inner "attribute" Dictionary Key-value"