Python: Trying to access different dictionaries in an imported file, based on variable given
Question: I have been making a simple turn based 'board game' in python using a separate
file to hold all of the data, such as what the attributes of a space is and
the attributes of the players. All of this is stored in separate dictionaries.
My problem lies in when I need to access or change data for specific players.

So far I have been doing it like this just so I can get it working and just
focus on making it work:

    
    
    def function(self): #self is the player number for that turn
        if self == 1:
            database.player1.update(data=0)
        if self == 2:
            database.player2.update(data=0)
    ...
    

and so on for all four players.

So what I tried to do instead was have something that went like this:

    
    
    def function(self):
        a = 'player' + (self)
        database.a.update(data=a)
    

However unsurprisingly this won't work, but is there a way to get something
like this where I am able to determine which dictionary to access based on
self?


Answer: Use getattr

    
    
    def function(self):
        a = 'player'+str(self)
        getattr(database,a).update(data=0)
    

`getattr` takes two arguments - the first is the object on which to retrieve
the attribute (in your case your `database` module), the second is the name
(string) of the attribute to retrieve (in your case `"player1"`, `"player2"`,
etc).

