简体   繁体   中英

Problem with loops in python dictionaries

I am new to python so maybe my problem is easy to solve.

I am having a hard time understanding the dictionaries and how to get only the number(integer) out that I want to compare with. I have googled for 8 hours and my head hurts a bit.

The error I get: TypeError: '>' not supported between instances of 'list' and 'int'

Here is my code:

dictionary1 = {
  "name": ["a", "b", "c"],
  "price": [55, 100, 25]
}

highest_price = 0
winner = ""

for value in dictionary1:
    bid_amount = dictionary1["price"]
    if bid_amount > highest_price:
        highest_price = bid_amount
        winner = name1[name]

print(f"the winner is: {winner}. With {highest_price}")

Technical problem

This first line in your for loop doesn't return one price as an integer but the whole price list. This dictionary1["price"] gives you [55, 100, 25] .

Logical problem

Data structure

I think you misunderstood how a dictionary work. In your case it seems the best to use a dictionary with a structure where the prices are the values and the names are the keys.

better_dict = {
    'a': 55,
    'b': 100,
    'c': 25}

In the solution code below I transform your dict via dict(zip(...)) into that form.

Iterate over a dictionary

When you iterate over a dictionary with a for loop you only get the keys not the values. In my example you have the keys ['a', 'b', 'c'] . When you want to access the values in a dictionary you have to use the key inside the loop.

Solution

This solutions tries to modify your code as less as possible.

#!/usr/bin/python3
dictionary1 = {
  "name": ["a", "b", "c"],
  "price": [55, 100, 25]
}

# transform your dict into an easier structure
better_dict = dict(zip(dictionary1["name"], dictionary1["price"]))
# result --> {'a': 55, 'b': 100, 'c': 25}

highest_price = 0
winner = ""

for name in better_dict:  # --> ['a', 'b', 'c']
    # get the value by key/name
    bid_amount = better_dict[name]
    if bid_amount > highest_price:
        highest_price = bid_amount
        winner = name  # use the key as name

print(f"the winner is: {winner}. With {highest_price}")

Alternative solution

Here you have an alternative approach without using a for loop. It also uses the transformed data structure.

#!/usr/bin/python3
dictionary1 = {
  "name": ["a", "b", "c"],
  "price": [55, 100, 25]
}

better_dict = dict(zip(dictionary1["name"], dictionary1["price"]))
# result --> {'a': 55, 'b': 100, 'c': 25}

# Find key with highest price
winner = sorted(better_dict, key=lambda k: better_dict[k])[-1]
# Get highest price by winners name
highest_price = better_dict[winner]

print(f"the winner is: {winner}. With {highest_price}")

I will try to break down the winner = line for you. sorted(better_dict) (without key= .) would return the keys (names) of the dictionary. But you want the values. So key=lambda k: better_dict[k] tell the sorted() to use the lambda function that returns the value of an element indexed by a key k . Because sorted() use ascending (lowest to highest price) order by default we use the last element of the returned list to get the name with the highest price. You can access the last element of a list via [-1] .

Inline:

dictionary1["name"][dictionary1["price"].index(max(dictionary1["price"]))]
  1. I would rearrange the structure of your dict, so that the letters a, b, c are the keys and the numbers are the values

    dictionary1 = { "a": 55, "b": 100, "c": 25 }
  2. You can sort the dictionary by value and reverse the sorting order so that the entry with the highest key is at the first position. This can be done by using the sorted function. There you have to set the key argument on dictionary1.get to sort by value and also set the reverse parameter on true. Finally you have to access the first element and the key with the highest value will be returned.

    sorted(dictionary1, key=dictionary1.get, reverse=True)[0]

Here ist the complete code:

dictionary1 = {
    "a": 55,
    "b": 100,
    "c": 25
}
max_entry = sorted(dictionary1, key=dictionary1.get, reverse=True)[0]

print(f"the winner is: {max_entry}. With {dictionary1[max_entry]}")

And the reason why you get this error is, because you try to compare the whole list "price" with the variable highest_price

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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