Python 3.x 从python3中的子ct读取

Python 3.x 从python3中的子ct读取,python-3.x,keyerror,Python 3.x,Keyerror,我有两个目录,一个是本地玩家数据,另一个是子目录中的玩家列表: class GameData: def __init__(self): self.player = {'id' : 1453339642, 'positionX' : 123, 'positionY' : 0

我有两个目录,一个是本地玩家数据,另一个是子目录中的玩家列表:

      class GameData:
        def __init__(self):
          self.player  =  {'id'           : 1453339642,
                           'positionX'    : 123,
                           'positionY'    : 0
                          }

          self.players =  {1453339642:
                                  {'name'         : "Admin"}
                          }
     gameData = GameData()
然后我打印出来只是为了检查是否一切正常:

            for x in gameData.player:
                print (str(x),':',gameData.player[x])

            print("\n\n")

            for x in gameData.players:
                print (str(x))
                for y in gameData.players[x]:
                    print ('    ',y,':',gameData.players[x][y])
            print("\n\n")
这导致:

            id : 1453339642
            positionY : 0
            positionX : 123

            1453339642
                 name : Admin
当我现在想要访问玩家的id时,例如使用

            #print(str(type(gameData.player)))
            #print(str(type(gameData.players)))
            print(str(type(gameData.players[1453339642])))

结果,我得到了KEYERROR。为什么?

如果我把它放在一个文件中,它会工作:

class GameData:
    def __init__(self):
        self.player  =  {'id'           : 1453339642,
                         'positionX'    : 123,
                         'positionY'    : 0
        }

        self.players =  {1453339642:
                         {'name'         : "Admin"}
        }
gameData = GameData()
print(str(type(gameData.players[1453339642])))

只有缩进与代码不同。在实例化和最终打印之间,
gameData
一定发生了什么事,
gameData

gameData=gameData()
缩进是否正确?是的,我只是将它错误地复制到stackoverflow框中。正如你所看到的,dict和sub-dict都在那里,我可以把它打印出来。不知何故,我无法访问指定的密钥?打印结果中有一些奇怪的东西:
positionX
应该是
123
。我重新输入了你的代码,它工作了。在实例化和最终打印之间,
gameData
是否有任何变化?是的。抱歉,现在也更正了。我现在检查了所有类型:播放器中的1453339642是int,但播放器中是字符串。我如何在播放器中将其转换为str?是的,这绝对是我的问题,因为它将dict键创建为字符串。这个工作原理是:打印(str(type(gameData.players[str(1453339642)]))我不太明白。查看您的代码,
gameData.player['id']
是一个int(值周围没有引号)。这与
gameData.players
中的
1453339642
相同:它是一个int,因为它周围没有引号。是的,我从一个更大的项目中总结了它。在这个项目中,我将gameData.players.update({ID)添加到dict中,然后它将其创建为字符串,原因是我仍然无法获取。我明白了。您可以使用
int(ID)
转换为int。此外,您可以只
打印(gameData.players)
,然后查看您的键是字符串还是数字。