0

I have a long list of variables to define (~100). Define as follows:

provider = node.xpath("//provider/text()")[0]
language = node.xpath("//language/text()")[0]
subtype = node.xpath("//subtype/text()")[0]
etc...

How would I define it more concisely/DRY, something like -

COLUMN_VARIABLES = ['provider', 'language','subtype']

for variable in COLUMN_VARIABLES:
    variable = node.xpath("//%s/text()"%variable)[0] 

3 Answers 3

6

The more concise way to do this would be to use a dictionary:

COLUMN_VARIABLES = ['provider', 'language','subtype']
data = {}

for variable in COLUMN_VARIABLES:
    data[variable] = node.xpath("//%s/text()"%variable)[0] 

Pro tip: any time you find yourself wanting to use variable variable names, it means you don't want variables, you want one container to hold all that data instead.

Sign up to request clarification or add additional context in comments.

Comments

3

Use a dictionary:

COLUMN_VARIABLES = ['provider', 'language','subtype']

vars = {}    
for variable in COLUMN_VARIABLES:
    vars[variable] = node.xpath("//%s/text()"%variable)[0] 

Comments

1

Use a dict to hold the results:

column_vars = ['provider', 'language','subtype']
nodes = {}

for var in column_vars:
    nodes[var] = node.xpath("//%s/text()" % variable)[0] 

Comments

Your Answer

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.