1

In the code below I create a dictionary 3 times and then attempt to change the value of Ontrade from True to False on Strategy 2 with the alteration function. However it does not work as expected and turns all the Ontrade values into True. How would i be able to fix that?

import numpy as np
import pprint 

listrange = 5
data = {}
dict_integrity = {"Array": np.array([]), "last_timestamp": 0, "last_Trades": 0, "Order_id_list": 0, "Ontrade": False, "TakeProfits": 0, "StopLoss": 0}

for x in range(listrange):
    data["Strategy " + str(x)] = dict_integrity

alteration = data["Strategy " + str(2)]["Ontrade"] = True

Output:

{'Strategy 0': {'Array': array([], dtype=float64),
                'Ontrade': True,
                'Order_id_list': 0,
                'StopLoss': 0,
                'TakeProfits': 0,
                'last_Trades': 0,
                'last_timestamp': 0},
 'Strategy 1': {'Array': array([], dtype=float64),
                'Ontrade': True,
                'Order_id_list': 0,
                'StopLoss': 0,
                'TakeProfits': 0,
                'last_Trades': 0,
                'last_timestamp': 0},
 'Strategy 2': {'Array': array([], dtype=float64),
                'Ontrade': True,
                'Order_id_list': 0,
                'StopLoss': 0,
                'TakeProfits': 0,
                'last_Trades': 0,
                'last_timestamp': 0}}

Expected Output:

{'Strategy 0': {'Array': array([], dtype=float64),
                'Ontrade': False,
                'Order_id_list': 0,
                'StopLoss': 0,
                'TakeProfits': 0,
                'last_Trades': 0,
                'last_timestamp': 0},
 'Strategy 1': {'Array': array([], dtype=float64),
                'Ontrade': False,
                'Order_id_list': 0,
                'StopLoss': 0,
                'TakeProfits': 0,
                'last_Trades': 0,
                'last_timestamp': 0},
 'Strategy 2': {'Array': array([], dtype=float64),
                'Ontrade': True,
                'Order_id_list': 0,
                'StopLoss': 0,
                'TakeProfits': 0,
                'last_Trades': 0,
                'last_timestamp': 0}}
ChristopherOjo
  • 237
  • 1
  • 12
  • Hi @ChristopherOjo, are you familiar to the concepts of _pass by reference_ and _pass by value_? – cmolina Jul 25 '21 at 02:40
  • You assign the **same** value `dict_integrity` to the dictionary three times. Make a copy of `dict_integrity` before the assignment. – DYZ Jul 25 '21 at 03:31
  • I am not familiar with that @cmolina and the point of assigning dict_integrity 3 times is to make sure they all have the same variables. How would I make a copy of it before the assignment? From my understanding of these comments, I am somehow passing the reference of the dictionary 3 times instead of only passing the values of the dictionary which is what I want. How do I fix this? – ChristopherOjo Jul 26 '21 at 14:55

0 Answers0