简体   繁体   English

如何在条件语句中使用嵌套在列表中的字典键值对的值?

[英]How do I use the value of a key-value pair of a dictionary nested inside a list in a conditional statement?

I searched a lot of similar posts on stack overflow, but I was not able to find anything even close to my particular issue, Forgive me in advance if this was asked and answered before.我搜索了很多关于堆栈溢出的类似帖子,但我找不到任何与我的特定问题相近的东西,如果之前有人问过并回答过,请提前原谅我。

I started learning Python programming 5 days ago and right now I'm trying to make a particular program which does a blind election.我在 5 天前开始学习 Python 编程,现在我正在尝试制作一个进行盲选的特定程序。 I take the inputs - name and bid amount and store them as a dictionary in a list.我接受输入 - 名称和出价金额并将它们作为字典存储在列表中。 Multiple such inputs lead to a list with a lot of dictionaries nested within it.多个这样的输入会导致一个列表,其中嵌套了很多字典。 I defined a function which loops through the different inputs in the final list of dictionaries and finds out the highest bid.我定义了一个 function 循环遍历最终字典列表中的不同输入并找出最高出价。

From my understanding and as confirmed in this post, I need to first index the correct element in the first square brackets and then point to the required key in the next square brackets.根据我的理解并在这篇文章中确认,我需要首先在第一个方括号中索引正确的元素,然后在下一个方括号中指向所需的键。

I had implemented this in my code but I get this particular error nonetheless.我已经在我的代码中实现了这一点,但我还是得到了这个特殊的错误。

```Traceback (most recent call last):
    File "main.py", line 36, in <module>
      blind_auction_result()
    File "main.py", line 14, in blind_auction_result
      if (total_bids[bidder]["amount"]) > max_bid:
TypeError: list indices must be integers or slices, not dict```

The code that I used is as follows:我使用的代码如下:

from replit import clear
from art import logo
total_bids = []
auction_active = True
def blind_auction_input(name,bid):
    auction_bids = {}
    auction_bids = {"name": name, "amount": bid}
    total_bids.append(auction_bids)
    print(total_bids)
def blind_auction_result():
    max_bid = 0
    bid_index = 0
    for bidder in total_bids:
        if (total_bids[bidder]["amount"]) > max_bid:
            max_bid = total_bids[bidder]["amount"]
            bid_index = bidder
    # print(f"The winner of this auction is {total_bids[bid_index]["name"]} who bid {total_bids[bid_index]["amount"]} $")
print(logo)
print("Welcome to todays' blind auction !")
while auction_active:
    bidder_name = input("What is your name?\n").lower()
    bid_amount = round(int(input("How much is your bid?\n")),2)
    while type(bid_amount) != int:
        bid_amount = round(int(input("Invalid input. Please enter a valid number.\n")),2)
    blind_auction_input(bidder_name,bid_amount)
    user_choice = input("Are there more bidders? Y or N.\n").lower()
    while not user_choice == "y" and not user_choice == "n":
        user_choice = input("Invalid input. Try again. Are there more bidders? Y or N.\n").lower()
    if user_choice == "y":
        auction_active = True
        clear()
    elif user_choice == "n":
        break
blind_auction_result()

Also, there is a line that I have commented out because apparently that was also showing an error, and I was able to run this only after commenting it out.另外,有一行我已经注释掉了,因为显然这也显示了一个错误,我只有在注释掉它之后才能运行它。 I'm out of ideas on how to solve this particular case, some help would be much appreciated:)我对如何解决这个特殊情况一无所知,非常感谢一些帮助:)

Just change that loop in blind_auction_result into只需将blind_auction_result中的循环更改为

    for bidder in total_bids:
        if bidder["amount"] > max_bid:
            max_bid = bidder["amount"]

for bidder in total_bids means that you're iterating through list items and use each item in each step. for bidder in total_bids意味着您正在遍历列表项并在每个步骤中使用每个项目。 So no need to fetch them again.因此无需再次获取它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查字典中是否存在键值对? 如果一个键的值是字典 - How do I check if a key-value pair is present in a dictionary? If the value of one key is a dictionary 如何将现有列表转换为 Python 中字典的键值对? - How to turn an existing list into a key-value pair for a dictionary in Python? 如何从基于另一个键值对的列表中的字典中访问值? - How to access values from a dictionary inside a list based on another key-value pair? 查找字典是简单键值对还是嵌套字典 - Find whether dictionary is simple key-value pair or nested dicts 如何在Python中打印截断的键/值对? - How do I print a truncated key-value pair in Python? 将嵌套列表与字典键进行比较并创建复合键值对 - Comparing nested list with dictionary keys and create compound key-value pair 如果事先不知道层次结构中的键位置,如何访问嵌套的Python字典键-值对? - How to access a nested Python dictionary key-value pair when the key location in the hierarchy is not known in advance? 如何从键值对列表构建字典? - How do I build a dict from key-value pair list? Python:如何匹配键,然后将键值对值的值与另一个字典中的值相乘? - Python: How do I match keys then multiply the values of a key-value pair value with values from another dictionary? 尝试访问嵌套字典中的键值对:我哪里出错了? - Trying to access a key-value pair in a nested dictionary: where am I going wrong?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM