I have create dictionary d
inside the function ic_strategy_2
. ic_strategy_2
is iterated for each elements in list using for
loop, which will create 3 dictionary
.
When below code is tested, only single dictionary
is getting printed though I append it in for
loop.
I want to append multiple dictionary
created from d
into one new dictionary as shown in expected output.
Thanks. Below is sample code.
Code-
# !pip install sorcery
from sorcery import dict_of
def ic_strategy_2(first,second,third,fourth):
global d
risk_reward_ratio = 10
max_profit = 20
nf_wed_range_pct = 30
d = dict_of(risk_reward_ratio,max_profit ,nf_wed_range_pct)
lst = [[300,150,50,50],[200,300,50,50],[250,250,50,50]]
for item in lst:
ic_strategy_2(*item)
dicts = []
dicts.append(d)
dicts
Output-
[{'max_profit': 20, 'nf_wed_range_pct': 30, 'risk_reward_ratio': 10}]
Expected Output-
[{'max_profit': 20, 'nf_wed_range_pct': 30, 'risk_reward_ratio': 10},{'max_profit': 20, 'nf_wed_range_pct': 30, 'risk_reward_ratio': 10},{'max_profit': 20, 'nf_wed_range_pct': 30, 'risk_reward_ratio': 10}]
CodePudding user response:
First of all, your description is that you'd like to create "one large dictionary", but your expected output example is a list of dictionaries. I'll go by the expected output example, assuming that's what you meant.
Also, you're reinitializing your dicts list in the loop.
You're also using hard-coded values for the dictionary, and not using your input. I'll assume this is a mistake; both in the code, and in the example-output...
And last but not least, a much simpler way to go around this would be to disregard the usage of global
which isn't really required here, and just use the more standard return
.
Putting it all together, I would suggest something like:
# !pip install sorcery
from sorcery import dict_of
def ic_strategy_2(first,second,third,fourth): # You aren't using your outputs. Is this purposeful? "fourth" especially seems unused...
risk_reward_ratio = first
max_profit = second
nf_wed_range_pct = third
d = dict_of(risk_reward_ratio,max_profit ,nf_wed_range_pct)
return d
lst = [[300,150,50,50],[200,300,50,50],[250,250,50,50]]
dicts = []
for item in lst:
d = ic_strategy_2(*item)
dicts.append(d)
print(dicts)