How to use a variable value as part of a variable name in python?

Question:

I was wondering if there was a way to have a variable value as part of another variable name in python. I have my code here, but I think there should be a way to make it a lot cleaner:

if self.player.dir == 'UP':
    self.player.image = self.player.image_up[0]
if self.player.dir == 'DOWN':
    self.player.image = self.player.image_down[0]
if self.player.dir == 'LEFT':
    self.player.image = self.player.image_left[0]
if self.player.dir == 'RIGHT':
    self.player.image = self.player.image_right[0]

I was thinking if we could have the value of dir as part of the self.player.image_(dir)[0]. I am not sure how I would do this though. It would look something like this I think:

self.player.image = self.player.image_(dir)[0]

Answers:

something like this might be what you are looking for:

images = {
    "UP": self.player.image_up[0],
    "DOWN": self.player.image_down[0],
    "RIGHT": self.player.image_right[0],
    "LEFT": self.player.image_left[0]
}

self.player.image = images[self.player.dir]
Answered By: Almog-at-Nailo

Using Python dictionary might be what you re looking for

self.player.image_ = {
     'UP':self.player.image_up[0],
     'DOWN': self.player.image_down[0],
     'LEFT':self.player.image_left[0],
     'RIGHT': self.player.image_right[0]
}
self.player.image = self.player.image_[self.player.dir]
Answered By: 3UX1N3
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.