receiving "TypeError: list indices must be integers or slices, not dict" when calling a value within a dictionary within a list

receiving "TypeError: list indices must be integers or slices, not dict" when calling a value within a dictionary within a list

我有以下用于无声拍卖程序练习的代码:

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
       

entries_list 的格式如下:

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

entries_list 中打印一个值工作正常:

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

但是,当我在 for 循环的 if 语句中引用它时:

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

我得到一个 TypeError: list indices must be integers or slice, not dict

有什么想法吗?

因为您已经在循环 entries_list 字典,所以您可以直接切片

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

应该可以。