0

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
2
  • 1
    Your attributes don't match the dict keys: Constants.fields_dict["sex"][1], self.player.name (sex and name). Is that a mistake? Commented Apr 17, 2018 at 23:31
  • Wow. Thank you. You just identified a bug that has been plaguing me for a day Commented Apr 17, 2018 at 23:33

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, perfect. Thanks Ding. Didn't know about this
@Parseltongue Np, glad it helps! :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.