You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中按plyoffStats[0]对嵌套结构字典排序失败的问题求助

Fixing Your Dictionary Sorting Issue for NFL Playoff Stats

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']
  1. Again, v[0] is the team name string, so trying to index it with ['plyfOffStats'] throws string indices must be integers—you can't use dictionary keys on a string.
  2. There's a spelling mistake: plyfOffStats should be plyoffStats (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 from dict2.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 with plyoffStats)
  • item[1][0]['plyoffStats'][0] = the first value in the plyoffStats list (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 06:32:43