Home > front end >  I am trying to print out the highest bidder in my list of dictionaries
I am trying to print out the highest bidder in my list of dictionaries

Time:01-13

I am trying to loop through my list of dictionaries and print out the highest bidder in my list of dictionaries. In a for loop with python is 'i' not automatically an integer?

Example : for i in dictionary: Does i not equal 0, 1, 2 so on?


bidders = [
{
  "name": "nicholas",
  "bid": 12,
},
{
  "name": "jack",
  "bid": 69,
},
]

for i in bidders:
        bid = bidders[i]["bid"]
        name = bidders[i]["name"]
        
        if bid > bid:
            print(f"Congratulations {name}! Your bid of ${bid} wins!")
        else:
            print(f"Congratulations {name}! Your bid of ${bid} wins!")

CodePudding user response:

You can use enumerate to range through a list and get the current index. Fixing your for loop, it would look like this:

for idx, _ in enumerate(bidders):
    bid = bidders[idx]["bid"]
    name = bidders[idx]["name"]

CodePudding user response:

No, since you are not calling the range function i is not default a integer. Leonardo's answer looks more correct, however what I wrote down below would also work.

bidders = [
    {
      "name": "nicholas",
      "bid": 12,
    },
    {
      "name": "jack",
      "bid": 69,
    },
]

maxBid = -1
maxBidName = "";

for i in range(0, len(bidders)):

    bid = bidders[i]["bid"]
    name = bidders[i]["name"]

    if bid > maxBid:
        maxBid = bid
        maxBidName = name
        

print(f"Congratulations {maxBidName}! Your bid of ${maxBid} wins!")

CodePudding user response:

there are few mistakes, i think this will works

bidders = [
{
  "name": "nicholas",
  "bid": 12,
},
{
  "name": "jack",
  "bid": 69,
},
]

highestBid = 0
highestBidData = {}

for i in bidders:
    if i['bid'] > highestBid:
        highestBid = i['bid']
        highestBidData = i
        
print("Congratulations {0}! Your bid of {1} `enter code 
here`wins!".format(highestBidData['name'],highestBidData['bid']))

CodePudding user response:

I believe what you’re looking for is bid = i[‘bid’]. i in this case is simply part of the dictionary. So for each entry, you want the value of ’bid’.

  •  Tags:  
  • Related