0

I'm sure this is something simple I'm missing, but with the code I have there is a list of dictionaries. I iterate over the list and update the dictionary items one by one. However, in the end I'm left with a list of all the exact same dictionary. I recreated the issue with barebones script and it still happens, so I'm thinking it's something to do with how I'm referring to the items.

import random

MyDict = {
    'Name': '',
    'Address': '',
    'SSN': ''
    }

Rows = []

Rows = [MyDict] * 5

print('We iterate through each item, and change the SSN value to a random number, printing as we go')
for i in range(len(Rows)):
    Rows[i]['SSN']= random.randint(0,999)
    print(Rows[i])

print('Printing at the end, and they are now all the same.')
for i in Rows:
    print(i)
  • 2
    You have 5 references to the same dictionary, not 5 copies of the dictionary. – Barmar Sep 07 '21 at 22:14
  • 2
    "a list of all the exact same dictionary" is precisely what `[MyDict] * 5` creates. You'd need something like `[MyDict.copy() for _ in range(5)]`. – jasonharper Sep 07 '21 at 22:15

1 Answers1

-2

Might be easier to do whatever you're doing with a pandas to convert simply

import pandas as pd
MyDict=#your dictionary
df=pd.Dataframe(MyDict)
df['ssn_transform']=df['ssn']*5

To answer your question directly rows is an empty list when you're trying to multiply it so it doesn't do anything

import random

MyDict = {
    'Name': '',
    'Address': '',
    'SSN': ''
    }

Rows = []

print('We iterate through each item, and change the SSN value to a random number, printing as we go')
for i in range(len(Rows)):
    Rows[i]['SSN']= random.randint(0,999)
    print(Rows[i])
#####
Rows = [MyDict] * 5
####
print('Printing at the end, and they are now all the same.')
for i in Rows:
    print(i)
tjaqu787
  • 295
  • 2
  • 16
  • The `pandas` code doesn't seem to do the same thing that OPs code is attempting to do. And your second code block wont run because Rows is empty making `range(len(Rows))` an empty iterator. And the second part has the same issue as OPs code with 5 references to the same dictionary. – Henry Ecker Sep 07 '21 at 22:24