0

I want to value the following dict y1~y10[name] with the given list.

I know using eval(self.y$i[name]) = value is wrong but how should I do this in python?

class excel: def __init__(self): self.base_year = 2004 self.y1 = {'year':self.base_year} self.y2 = {'year':self.base_year + 1} self.y3 = {'year':self.base_year + 2} self.y4 = {'year':self.base_year + 3} self.y5 = {'year':self.base_year + 4} self.y6 = {'year':self.base_year + 5} self.y7 = {'year':self.base_year + 6} self.y8 = {'year':self.base_year + 7} self.y9 = {'year':self.base_year + 8} self.y10 = {'year':self.base_year + 9} def value(self, name, value_list): for value, i in value_list, range(1, 10): eval(self.y$i[name]) = value list = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 ] e1.value('test', list) 
1
  • 6
    Why don't you just make a list or dict called self.y? Then you wouldn't need eval() or similar things in the first place. Commented Dec 29, 2014 at 3:53

3 Answers 3

6

The temptation to use introspection &c for mundane tasks is a strong code smell which suggests rethinking your approach -- here, as others have mentioned, making self.y a list of dicts is a much better idea. You also need other fixes in your code, though.

class excel: def __init__(self): self.base_year = 2004 self.y = [{'year':self.base_year+i} for i in range(10)] def value(self, name, value_list): for i, value in enumerate(value_list): self.y[i][name] = value 

Yes, this self.y is base-0 (goes 0 to 9) -- that's inevitably a lot simpler in programming, and simplicity is such a precious virtue I wouldn't want to give it up...

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

Comments

4

No need to use eval when getattr will do:

getattr(self, 'y%u' % i)[name] = value 

But it would be better to put your y#s in a list. So that you can do:

self.y[i][name] = value 

Comments

0

I don't like using eval for this any more than Kevin or Dan D. do, but to answer your questions, you can use:

yi = eval( "self.y{0}".format(i) ) yi[name] = value; 

The eval() function evaluates an expression, but an assignment with =, +=, etc. is not an expression in Python. It's a statement. Thus, I used eval() go get the dict reference into a local variable (y) and used that reference to set the member of the dict that it references.

You can also glue those two statements together and eliminate the yi local variable:

eval("self.y{0}".format(i))[name] = value; 

However, like the others have said, this is not the best way to do this. A dict, list or even a tuple of dictionaries do the job better. (See Alex Martelli's example.)

1 Comment

Thank you and @Dan D. for point out my old way is bad and still gave out the answer. You guys are greats. Thanks again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.