Apologies if this is a silly question.
I have a list of potential dictionary keys here:
form_fields = ['sex',
'birth',
'location',
'politics']
I am currently manually adding values to these keys like so:
self.participant.vars["sex"] = [Constants.fields_dict["sex"][0], Constants.fields_dict["sex"][1], self.player.name]
self.participant.vars["birth"] = [Constants.fields_dict["birth"][0], Constants.fields_dict["birth"][1],self.player.age]
self.participant.vars["location"] = [Constants.fields_dict["location"][0], Constants.fields_dict["location"][1],self.player.politics]
I'd like to be able to do a use a for loop to do this all at once like so:
for i in form_fields:
self.participant.vars[i] = [Constants.fields_dict[i][0], Constants.fields_dict[i][1], self.player.`i`]
Obviously, however, I can't reference the object self.player.i like that. Is there a way to reference that object dynamically?
asked Apr 17, 2018 at 23:20
Parseltongue
11.7k31 gold badges106 silver badges172 bronze badges
1 Answer 1
use getattr, For example, getattr(x, 'foobar') is equivalent to x.foobar.
for i in form_fields:
self.participant.vars[i] = [Constants.fields_dict[i][0], Constants.fields_dict[i][1], getattr(self.player, i)]
answered Apr 17, 2018 at 23:29
Bubble Bubble Bubble Gut
3,37617 silver badges30 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Parseltongue
Ah, perfect. Thanks Ding. Didn't know about this
Bubble Bubble Bubble Gut
@Parseltongue Np, glad it helps! :)
lang-py
Constants.fields_dict["sex"][1], self.player.name(sexandname). Is that a mistake?