0

I have a problem where after the outer loop ends, both dictionaries point to the same values. I have code of the sort:

for state in states:
    probab_dist = numpy.random.dirichlet(some args..).flatten()
    for i, j in zip(word, range(len(word))):
        state.dict[i] = probab_dist[j]

I inserted a print statement after line 2 to see whether the dirichlet function just returns the same value every single time. It didn't, and sure enough printing the value of the dictionary of each state after the inner loop exits showed that at first each state's dictionary has its own values.

I figured it might be a deep copy vs shallow copy kind of problem so I replaced line 4 with state.dict[i] = copy.deepcopy(probab_dist[j], but that didn't change anything.

Any ideas what I could try next?

8
  • 1
    I think you can replace that zip with enumerate, a built-in that returns an integer index along with each element in the iterable.
    – aghast
    Commented May 7, 2016 at 19:58
  • Did you mean mean replace the range(len())? If so, thanks, I replaced it. Any idea how I can deal with my other problem?
    – user8814
    Commented May 7, 2016 at 20:03
  • 1
    No, sorry. In fact, I'm unclear on what the problem is. What is probab_dist[j]? Isn't it a number?
    – aghast
    Commented May 7, 2016 at 20:07
  • 1
    Also, seems like you could just zip up the word and the probab_dist array to get your key/value pairs: state.dict = {k:v for k,v in zip(word, probab_dist)}
    – aghast
    Commented May 7, 2016 at 20:09
  • Yes, it's a list of numbers. The first time the loop runs, the value of probab_dist is [ 0.06690239 0.58836214 0.09368838 0.09415571 0.15689137], and when I check the values of the first state's dictionary at the end of the outer loop, it is also the same. The second time the loop runs, the value of probab_dist is [ 0.07864053 0.20966494 0.04294388 0.04541454 0.62333611], and the second state's dictionary has that value. However, once the loop exits, both states' dictionaries default to the second state's values.
    – user8814
    Commented May 7, 2016 at 20:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.