Home > Back-end >  Search for a specific value in a nested list dictionary (Python)
Search for a specific value in a nested list dictionary (Python)

Time:03-23

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 = []

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()

CodePudding user response:

Lists are iterable in Python, meaning you can loop over them for searching purposes. 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. That could be addressed by tracking the insertion order of placed bids.

LoD (List of Dictionaries) For-Loop Example:

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!')

CodePudding user response:

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)
  • Related