Casey
Casey

Reputation: 552

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 could sort it using this code:

players = [(k, players[k]) for k in sorted(players, key=players.get, reverse=True)]

But now since I implemented the inner "attribute" dictionary, I get an error saying comparisons can't be made on dictionaries.

TypeError: '<' not supported between instances of 'dict' and 'dict'

So how can I modify the sorting method to compare values of the dictionaries (the roll_total values), and have my players dictionary sorted?

Upvotes: 2

Views: 3243

Answers (2)

Tim Pozza
Tim Pozza

Reputation: 548

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)}

Upvotes: 1

Rik
Rik

Reputation: 477

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'].

Upvotes: 2

Related Questions