【问题标题】:receiving "TypeError: list indices must be integers or slices, not dict" when calling a value within a dictionary within a list在调用列表中的字典中的值时收到“TypeError:列表索引必须是整数或切片,而不是字典”
【发布时间】:2021-12-15 00:39:20
【问题描述】:

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

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
       

entry_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 slices, not dict

有什么想法吗?

【问题讨论】:

    标签: python list dictionary typeerror calling-convention


    【解决方案1】:

    由于您已经在循环 entries_list 字典,因此您可以对其进行切片

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

    应该可以。

    【讨论】:

    • 当然!我已经在遍历条目,我必须降低 1 个“级别”。谢谢! :)
    猜你喜欢
    • 2016-09-19
    • 2017-04-12
    • 2020-06-17
    • 2022-10-04
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    相关资源
    最近更新 更多