Reputation: 43
I have dictionary like this:
team_dict = {
'Iran': {
'wins':ir_win,
'loses':ir_lose,
'draws':ir_draws,
'goal difference':ir_goal,
'points':ir_score
},
'Spain': {
'wins':sp_win,
'loses':sp_lose,
'draws':sp_draws,
'goal difference':sp_goal,
'points':sp_score
},
'Portugal': {
'wins':po_win,
'loses':po_lose,
'draws':po_draws,
'goal difference':po_goal,
'points':po_score
},
'Morocco': {
'wins':ma_win,
'loses':ma_lose,
'draws':ma_draws,
'goal difference':ma_goal,
'points':ma_score
}
}
Then I sorted it:
sorted_team_dict = sorted(
team_dict.items(),
key = lambda x: (-x[1].get('points'), -x[1].get('wins'), x[1].get('keys')
)
)
I want to print the sorted one by:
for item in sorted_team_dict:
print(
"%s wins:%i , loses:%i , draws:%i , goal difference:%i , points:%i" % (
sorted_team_dict[item]["keys"],
sorted_team_dict[item]["wins"],
sorted_team_dict[item]["loses"],
sorted_team_dict[item]["draws"],
sorted_team_dict[item]["goal difference"],
sorted_team_dict[item]["points"]
)
)
but I'm faced with the error below:
list indices must be integers or slices, not tuple
and I can't understand the meaning of error.
Upvotes: 1
Views: 84
Reputation: 719
The issue here is that sorted_team_dict
is not a dictionary, but a list of tuples. So you would iterate through it like so:
for key, value in sorted_team_dict:
print("%s wins:%i , loses:%i , draws:%i , goal difference:%i , points:%i" %(key,value["wins"],value["loses"],value["draws"],value["goal difference"],value["points"]))
And you should probably rename it to sorted_team_items
or something. The code could use other clean up as well, but that's outside of the scope of this question.
Upvotes: 1