0

I'm trying to in a for loop increment dictionary values and save that dictionary in a list, for each iteration in the for loop. For some reason all the dictionaries in the list end up being identical.

I tried multiple approaches, and using defaultdict.

Here is a simple example code:

from collections import defaultdict
randomList = []

initialValue = {"passCountH" : 0,
            "passCountUnsuccH" : 0,
            "shotCountH" : 0,
            "shotOnGoalH" : 0,
            "passCountA" : 0,
            "passCountUnsuccA" : 0,
            "shotCountA" : 0,
            "shotOnGoalA" : 0,
            "scoreH" : 0,
            "scoreA" : 0,
            "time" : 0,
            "finalOutcome" : 0
           }


for i in range(10):
    initialValue["passCountH"] += 1
    randomList.append(initialValue)

print(randomList[0])
df = pd.DataFrame(randomList)
print(df)

What I would want is that randomList[0] is the "first iteration" of the dictionary. i.e. value of passCountH to be = 1, randomList[1] to have passCountH = 2 etc.

But what I'm getting is 10 dictionaries in the list, with all of them being identical, with passCountH = 10.

Anton
  • 581
  • 1
  • 5
  • 23
  • "For some reason all the dictionaries in the list end up being identical" Because *you append the same dict every time*, right here: `randomList.append(initialValue)`. Why do you expect `initialValue` to be a different dict? – juanpa.arrivillaga Jan 16 '19 at 19:05
  • I see, so the dictionary gets updated inside the list? what would be the best approach to achieve what I'm looking to do? Append the values in a list and create a nested list, build dataframe by specifying its columns and feed the nested list? – Anton Jan 16 '19 at 19:08
  • You need to create a new dict that you append on each iteration. You could `.copy` the main dict at the dtop of the loop – juanpa.arrivillaga Jan 16 '19 at 19:09
  • Yeah that seems to work, thanks. – Anton Jan 16 '19 at 19:10

0 Answers0