Home > Mobile >  receiving "TypeError: list indices must be integers or slices, not dict" when calling a va
receiving "TypeError: list indices must be integers or slices, not dict" when calling a va

Time:11-02

I have the following code for a silent auction program exercise:

bidding = 1
entry_dictionary = {}
entries_list = []

while bidding:
    entry_dictionary = {}
    name = input("What is your name?\n")
    bid = int(input("What's your bid?\n$"))
    entry_dictionary["name"] = name
    entry_dictionary["bid"] = bid
    entries_list.append(entry_dictionary)
    print(entries_list)
    other_bidders = input("Are there any other bidders? Type 'yes' or 'no'\n")
    if other_bidders == "yes":
        
    else:
        bidding = 0
       

The entries_list has the following format:

entries_list = [
{
  "name": "john", 
  "bid": 100,
},
{
  "name": "Laura",
  "bid": 500,
},
]

Printing a value within the entries_list works fine:

print(entries_list[0]["bid"])     # output is "100"

However, when I reference it in an if statement in a for loop:

max_bid = 0
for entry in entries_list:
    if entries_list[entry]["bid"] > max_bid:
        print("itworks")

I get a TypeError: list indices must be integers or slices, not dict

any thoughts?

CodePudding user response:

Since you are already looping the entries_list dict you can just slice on that

for entry in entries_list:
    if entry["bid"] > max_bid:
        print("it works")

should work.

  • Related