Python中按plyoffStats[0]对嵌套结构字典排序失败的问题求助
Let's walk through what's causing your sorting problems and get you the correct ordered dictionary.
What's Wrong with Your First Attempt?
Your initial sorting code uses this lambda:
lambda v:v[0][0]
When you iterate over dict2.items(), each element v is a tuple like (team_name, team_data). So v[0] is the string name of the team, and v[0][0] is just the first character of that name. That's why your results were sorted seemingly randomly—they were ordered by the first letter of each team's name, not the playoff stat you wanted.
Why Did the Second Attempt Throw a TypeError?
Your second try had two issues:
lambda v:v[0]['plyfOffStats']
- Again,
v[0]is the team name string, so trying to index it with['plyfOffStats']throwsstring indices must be integers—you can't use dictionary keys on a string. - There's a spelling mistake:
plyfOffStatsshould beplyoffStats(capitalization error on the 'O').
The Correct Sorting Code
To sort by the first value in plyoffStats (the number of playoff wins, I assume), you need to target the right part of your data structure:
# Correctly sort by plyoffStats[0] in descending order sortedByWinPct2 = {k: v for k, v in sorted( dict2.items(), key=lambda item: item[1][0]['plyoffStats'][0], reverse=True )}
Let's break down the lambda:
item= each(team_name, team_data)tuple fromdict2.items()item[1]= the list of data for the team (e.g.,[{'plyoffStats': ...}, {'round': ...}])item[1][0]= the first dictionary in that list (the one withplyoffStats)item[1][0]['plyoffStats'][0]= the first value in theplyoffStatslist (your desired sorting key)
Verify the Result
If you print the sorted teams and their target stat:
for team, stats in sortedByWinPct2.items(): print(f"{team}: Playoff Wins = {stats[0]['plyoffStats'][0]}")
You'll get the correct ordered output:
Pittsburgh Steelers: Playoff Wins = 19 Seattle Seahawks: Playoff Wins = 14 Jacksonville Jaguars: Playoff Wins = 7 Houston Texans: Playoff Wins = 4 Miami Dolphins: Playoff Wins = 3 Buffalo Bills: Playoff Wins = 1
内容的提问来源于stack exchange,提问作者noobcoderiam

