0

I am writing to a dict key, but several other keys get changed as well.

This code:

lead_data = result2[q['lead']]['data']
man_data = result2[q['lead']]['mans'][q['man']]
total_data = result2['total']
for i in range(0, 4):
    w = 'w{n}'.format(n=i)

    trips = q['trips{n}'.format(n=i)]
    delta = q['delta{n}'.format(n=i)]
    print(trips)
    print(lead_data[w]['trips'])

    lead_data[w]['trips'] += trips
    print(lead_data[w]['trips'])

    man_data[w]['trips'] += trips
    print(lead_data[w]['trips'])

    total_data[w]['trips'] += trips
    print(lead_data[w]['trips'])

returns the following output (from print commands):

28
0
28
56
84
29
84
113
142
171
0
171
171
171
171
0
171
171
171
171

As you can see, the value of lead_data[w]['trips'] is changed with commands man_data[w]['trips'] += trips and total_data[w]['trips'] += trips as well. Which is extremely weird.

Anyone saw something similar?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Vémundr
  • 395
  • 1
  • 7
  • 17
  • @Chris yup, that helped. Why does that happen at all? I swear at my momma keys were not mixed up. A ton of similar structures, yes, but not mixed up. – Vémundr Dec 09 '18 at 23:33
  • 2
    It's not about being "mixed up", it's about what happens when you do `lead_data = result2[q['lead']]['data']` if `result2[q['lead']]['data']` is a dict. Try `foo = {}`, `bar = foo`, `foo['baz'] = True`, `print(bar)`. – ChrisGPT was on strike Dec 09 '18 at 23:37
  • @Chris Holy cow, I got it. I made a template dict and assigned it to every similar structure in the big dictionary Basically rendering every single dataset to the same memory object. Thank youm I can feel my brain growing. – Vémundr Dec 09 '18 at 23:59
  • 1
    I'm glad to hear it! That "brain growing" feeling is great, and it's what Stack Overflow is all about. – ChrisGPT was on strike Dec 10 '18 at 00:02

0 Answers0