I'm having problems with my for-loop and getting following message: KeyError: 2

I'm having problems with my for-loop and getting following message: KeyError: 2

我收到以下错误:Stats PlayerList=competitionList[j] KeyError: 2 我在 competitionList 中保存了很多列表,它是一个字典。我想遍历我字典中列表中的所有对象。

def Stats(competitionList, playerList):
        no_of_competitions = int(len(competitionList))
        x = (len(playerList))
        for i in range(no_of_competitions):
            for j in range (int(x)):
            #My error occurs here
                PlayerList=competitionList[j]
                for player in PlayerList: 
                    print("player: ", player.name)
                    print ("list :", player.name, player.victories)

错误只是在这一行中指出:

PlayerList=competitionList[j]

字典 competitionList 不包含 range(x) 中的键之一,在本例中为键 2。确保:

  1. 范围内的所有值都出现在 competitionList
  2. 或者您只迭代字典中实际存在的值

对于第二个选项,这应该可以简化事情并使它们起作用:

for players in competitionList.values():
    for player in players:
        print("player: ", player.name)
        print ("list : ", player.name, player.victories)

您使用 j 访问 competitionList。但是 j 指的是 xxplayerList 的长度。 playerListcompetitionList 可以延迟长度,所以这就是为什么你会得到这种类型的错误。