Home > database >  Appending a Dictionary to a List seems to overwrite instead
Appending a Dictionary to a List seems to overwrite instead

Time:11-30

I know I am relatively close to getting this but I can't seem to work out why when I add another bidder the list only contains the latest dictionary even though I am appending to that list. I also tried .copy() to no avail, what am I missing here?

import os
from art import logo
clear = lambda: os.system('clear')
myFlag = True

print("Welcome to the Silent Auction....")
print(logo)

while myFlag:
    silent_dict = []

    name = input("Enter your name, Bidder: ")
    bid = int(input("Enter your Bid: £"))


    def add_new_bid(name, bid):
        new_entry = {"name": name, "bid": bid}
        silent_dict.append(new_entry)
        print(silent_dict)
        


    clear()
    add_new_bid(name, bid)

    more_bids = input("Are there any more bidders? Type Yes or No: ")

    if more_bids == "No":
        myFlag = False
        break

It's confusing because previously I've used the following code to do something similar so maybe I'm just bad at indentation?

travel_log = [
{
  "country": "France",
  "visits": 12,
  "cities": ["Paris", "Lille", "Dijon"]
},
{
  "country": "Germany",
  "visits": 5,
  "cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]

def add_new_country(country, visits, cities):
    new_entry = {"country": country, "visits": visits, "cities": cities}
    travel_log.append(new_entry)

add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)

CodePudding user response:

You initialize silent_dict to an empty list at the beginning of each loop iteration, which would erase the previous one the next time you enter a bid. You should run silent_dict = [] before you enter your while loop.

  • Related