简体   繁体   中英

Python Auction House Calculate Winner

print("Welcome to the Auction House")
name = input("Enter your name: ")
price = int(input("Enter your price: "))

total_list = []
def store_data(name, price):
    name_list = {}
    name_list["name"] = name
    name_list["price"] = price
    total_list.append(name_list)

def compare(highest_bid):
    winner = 0
    winn = ""
    for someone in highest_bid:
        if highest_bid[someone] > winner:
            winner = highest_bid["price"]
            winn = winner
    print(winn)

store_data(name, price)
something = True
while something:
    question = input("Is there other who want to bid? (y/n) ").lower()
    if question == "y":
        name = input("Enter your name: ")
        price = int(input("Enter your price: "))
        store_data(name, price)
    else:
        compare(total_list)
        something = False

Hello everyone, I'm building an auction action and having this error. if highest_bid[someone] > winner:

TypeError: list indices must be integers or slices, not dict.

I have tried several ways of doing it such as adding a list in compare(), etc but still couldn't solve the problem. I want to make it like who has the highest bid then who will win in the auction house but, of course, I would add some description after that but right now my problem is I couldn't determine who the winner using my compare(). I appreciate it if you can help out with my small little project.

I fixed your code

def compare(highest_bid):
    winner = 0
    winn = ""
    for someone in highest_bid:
        if someone["price"] > winner:
            winner = someone["price"]
            winn = someone["name"]
    print(winn)

the problem is at compare function. here I fix it for you.

def compare(highest_bid):
    winner = 0
    winn = ""
    # for someone in highest_bid:
    #     if highest_bid[someone] > winner:
    #         winner = highest_bid["price"]
    #         winn = winner
    for someone in highest_bid:
        if someone["price"] > winner:
            winner = someone["price"]
            winn = winner
    print(winn)

You are trying to access dictionary but total_list is a list. You can continuously update name_list as

name_list = {}
def store_data(name, price):
    name_list.update({name : price})

And then in compare function access the values using keys.

def compare(highest_bid):
    winner = 0
    winn = ""
    for someone in highest_bid:
        if highest_bid.get(someone) > winner:
            winner = highest_bid.get(someone)
            winn = winner
    print(winn)

Pass name_list in compare function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM