1

I am trying to make a loop to add columns to existing variables (there are between 10 to 15 variables called option0, option1,...optionn). Each option variable has its own columns, but I need to add more columns to each variable. Doing it one by one is inefficient, doing it with a loop, does not work. Example for option0:

option0['Risk_rate'] = rfr.column[0]

Example for n options:

for opt in range(0, len(aapl.expiry_dates)):
     ['option%s' % opt['Risk_rate']] =  rfr.column[0]

A proper hint would be really handy and would save me a lot of inefficient code!

Cœur
  • 37,241
  • 25
  • 195
  • 267
nemi
  • 67
  • 1
  • 7
  • 1
    Don't have numbered `option` variables like that. Put them into a list, so you can access them via index. – PM 2Ring Nov 27 '15 at 15:12
  • Why not put all the optionX variables into a list and iterate over it, adding new data to them that way? – Maciek Nov 27 '15 at 15:12

2 Answers2

1

So as menthioned in comments you'd better have a list of variables instead of different named variables. In this case the code would be:

options = [dict() for i in range(number_of_options_you_need)]
#use options[0] instead of options0

#to set new key-value to all options
for opt in options:
    opt['Risk_rate'] = some_new_value
Leonid Mednikov
  • 943
  • 4
  • 13
  • Thank you! This was exactly was I was looking for, but did know how to go about it or ask google in a proper way! – nemi Nov 27 '15 at 15:56
0

Use metaprogramming:

foo0 = {}
foo1 = {}
foo2 = {}

for i in range(3):
    exec("foo{}['bar'] = 'baz'".format(i))
    exec('print(foo{})'.format(i))
macabeus
  • 4,156
  • 5
  • 37
  • 66
  • 2
    No. `exec` is a tool of last resort. It's slow and potentially dangerous. See [Why should exec() and eval() be avoided?](http://stackoverflow.com/q/1933451/4014959). – PM 2Ring Nov 27 '15 at 15:15
  • As much as I like the approach and creativity of your idea, I don't think that would be the best practice for such a simple problem. If the developer knows what collections are to be updated, it's much better to keep them in some kind of collection and iterate over that collection to update them. Also, I guess that would be much faster, as `exec` does a lot of work for a very simple task. – Maciek Nov 27 '15 at 15:16
  • If you know what you're doing, no problem. Depending on the case, it is better to use something that takes more processing, such as the exec, than something complicated to write and maintain. Furthermore, optimization is not always a design requirement. Moreover, in this case the exec does not have security holes, because the string to be executed is not determined by the user. – macabeus Nov 27 '15 at 15:20