简体   繁体   English

在嵌套列表字典中搜索特定值 (Python)

[英]Search for a specific value in a nested list dictionary (Python)

I'm coding a secret auction program, and in order to find the person with the highest bid, I need to search bidder_info for the last number of bidder_bids.我正在编写一个秘密拍卖程序,为了找到出价最高的人,我需要在 bidder_info 中搜索 bidder_bids 的最后数量。

bidder_info = []
bidder_bids = []

def secret_auction_program():
    num_bidders = 1
    name = input("What is your name? ")
    bid = input("What's your bid?")
    bid = int(bid)
    other_bidders = input("Are there any other bidders? Type 'yes' or 'no'. ")
    
    
    def add_info(name, bid):
    bidder_info.append({"name": name, "bid": bid})
    add_info(name, bid)
    print(bidder_info)
    bidder_bids.append(bid)


    if other_bidders == "yes":
    secret_auction_program()
    if other_bidders == "no":
    bidder_bids.sort()
    print(bidder_bids)
    
secret_auction_program()

Lists are iterable in Python, meaning you can loop over them for searching purposes.列表在 Python 中是可迭代的,这意味着您可以循环遍历它们以进行搜索。 In your case you have a list of dictionaries with known keys.在您的情况下,您有一个包含已知键的字典列表。 Use the known keys to search for your bid value.使用已知键搜索您的出价。 FWIW, as written there are no provisions for multiple bidders of the same value. FWIW,如所写,没有针对相同价值的多个投标人的规定。 That could be addressed by tracking the insertion order of placed bids.这可以通过跟踪已出价的插入顺序来解决。

LoD (List of Dictionaries) For-Loop Example: LoD(字典列表)For 循环示例:

myList = [{'key1': 'somestr1', 'key2': 1}, {'key1': 'somestr2', 'key2': 2}]

#loop over list and search dicts for some value

for item in myList:

    if item['key2'] == 2:
        print(f'success, {item['key1']} has key2 value of 2!')

I am giving a general solution to how to search for a specific value in a nested list dictionary with an example:我给出了一个关于如何在嵌套列表字典中搜索特定值的通用解决方案,示例如下:

Find any entry whether key or value in在中查找任何条目,无论是键还是值

mylist = [{'c': 3, 'd': 4}, {1: 'a', 'b': 2}]

for item in mylist:
    for key, value in item.items():
        if key == 'a' or value == 'a':
            print(True)

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

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