'Python dict.append in for loop adds last value as append for all
I'm trying to append a list of bank transactions. These contain 12 transactions, and I want that to be 100k+. Normally that wouldn't be an issue, but this time I'm somehow doing something wrong. I'm setting a single transaction as "example", and simply changing 3 values to something random:
# Set any transaction that can be updated with random values
transaction = df.accounts[0]['transactions'][0]
# Randomizing any amount of transactions and appending them to the dataframe
for i in range(10):
rand = round(random.uniform(-25000, 25000), 2)
res = transaction
res['transactionDate'] = random_date("2/22/2021 1:30 PM", "2/22/2022 4:50 AM", random.random())
res['classifyCategory'] = categories[round(random.random() * len(categories)) - 1]
res['amount'] = rand
print(res)
df.accounts[0]['transactions'].append(res)
This returns the following:
amount: -8664.93, date: 05/02/2021 11:43 AM, categorie: a
amount: -7433.14, date: 04/15/2021 01:51 PM, categorie: b
amount: 3905.45, date: 02/20/2022 04:34 AM, categorie: c
amount: -11755.49, date: 04/21/2021 07:44 AM, categorie: d
amount: 17833.53, date: 04/22/2021 07:07 PM, categorie: e
amount: -3694.67, date: 12/26/2021 01:02 PM, categorie: f
amount: 24981.7, date: 01/01/2022 10:25 PM, categorie: g
amount: 14045.01, date: 04/03/2021 06:18 PM, categorie: h
amount: 23642.71, date: 05/01/2021 12:38 PM, categorie: i
amount: 5687.76, date: 09/26/2021 01:41 AM, categorie: j
This simply adds 10 transactions with random transaction date, classification and amount. However, only the very last value of what this returns will be added 10 times to the transactions list:
amount: 5687.76, date: 09/26/2021 01:41 AM, categorie: j
amount: 5687.76, date: 09/26/2021 01:41 AM, categorie: j
amount: 5687.76, date: 09/26/2021 01:41 AM, categorie: j
amount: 5687.76, date: 09/26/2021 01:41 AM, categorie: j
amount: 5687.76, date: 09/26/2021 01:41 AM, categorie: j
amount: 5687.76, date: 09/26/2021 01:41 AM, categorie: j
amount: 5687.76, date: 09/26/2021 01:41 AM, categorie: j
amount: 5687.76, date: 09/26/2021 01:41 AM, categorie: j
amount: 5687.76, date: 09/26/2021 01:41 AM, categorie: j
amount: 5687.76, date: 09/26/2021 01:41 AM, categorie: j
I have no idea what's going wrong here. Does anyone have a clue how only the last value could be added for each item in the loop, even though it shouldn't even have that value when appending the previous ones?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
