Home > Back-end >  Assigning type of a dynamically generate variable to a list in a loop
Assigning type of a dynamically generate variable to a list in a loop

Time:02-14

I have a set of technical indicators in a list - indicator_list = [ema10,ema20,...] I am trying to generate a indicator series list which will hold the series value for each stock for each indicator as below -

indicator_ser_dict = {}
for indicator in indicator_list:
   indicator_ser_list = indicator   '_ser_list'
   indicator_ser_dict[indicator] = indicator_ser_list

How do I set the type of each indicator_ser_list to a list. That is each of the value in the indicator_ser_dict needs to be a list. Please note that indicator_ser_list needs to be treated as a variable and not a string.

CodePudding user response:

I am not sure if I get you right. I understand that you want every item-value in your indicator_ser_dict to be a single item list.

Given your examples, having ema10,ema20 as input you want to put ema10 into a list and place this single-item-list as value in the dictionary.

You can simply put the item to be listed into square brackets:

indicator_ser_dict = {}
for indicator in indicator_list:
   indicator_ser_list = [indicator   '_ser_list'] #-> makes indicator_ser_list  to be a list of one element
   indicator_ser_dict[indicator] = indicator_ser_list

Since ure concatenating a string to each indicator, the indicator_ser_list of course always was a string. Now its a List of a single string.

CodePudding user response:

Using the following method:

indicator_ser_dict = {}
for indicator in indicator_list:
    indicator_ser_list = indicator   '_ser_list'
    indicator_ser_dict[indicator] = indicator_ser_list
    indicator_ser_dict[indicator_ser_list] = []

With input list: [ema10, ema20] The output dictionary will look like:

indicator_ser_dict = {
    ema10: 'ema10_ser_list',
    ema10_ser_list = [],
    ema20: 'ema20_ser_list',
    ema20_ser_list = []
}

Alternatively, you could declare the list variable directly into the name of the indicator:

indicator_ser_dict = {}
for indicator in indicator_list:
    indicator_ser_dict[indicator] = []

For output dictionary:

indicator_ser_dict = {
    ema10: [],
    ema20: [],
}
  • Related