Search code examples
python-3.xkeyerror

Reading from subdict in python3


I have 2 dict. One with local player data and one listing the players with subdictionaries:

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

          self.players =  {1453339642:
                                  {'name'         : "Admin"}
                          }
     gameData = GameData()

Then I print out just to check if everything works:

            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")

This results in:

            id : 1453339642
            positionY : 0
            positionX : 123

            1453339642
                 name : Admin

When I now want to access the player's id in players for instance with

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

I get KEYERROR as a result. Why?


Solution

  • If I put this in a file, it works:

    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])))
    

    Only indentation differs from your code. There must be something happening to gameData between instantiation and the final print.