Skip to content
Advertisement

Python, how to sort this dictionary right?

I started 100 days of code and this project is a silent auction (day 9). You take a user’s name and bid price, store it in a dictionary, and then clear it (prompting to see if there are other users). The whole point is to collect the keys/values (that are unknown) and sort them so that it prints the highest value (bidder).

Since I don’t know what the keys or values in the dictionary would be I wanted to sort the dictionary after the “No” prompt. Then I decided to convert the dictionary to a list so I can access the keys and values separately. The reason I needed to do this was because in the print statement I print the name (key) and bid price (value) in different parts of the sentence.

Example inputs:

{'alan': '115', 'jay': '125', 'alex': '155'} ['alan', 'jay', 'alex'] ['115', '125', '155']

Output: The winner is alex with a bid of $155.

I run into an error though when the user enters $5 as an input:

{'john': '105', 'alex': '115', 'jae': '5'} ['john', 'alex', 'jae'] ['105', '115', '5']

The winner is jae with a bid of $5.

Also another error “Local variable referenced before assignment” in regard to key_list and key_value. The solution I read was to write global at the beginning of the function.

    from replit import clear
    from operator import itemgetter
    #HINT: You can call clear() to clear the output in the console.
    from art import logo 
    print(logo)
    
    bid_dictionary = {}
    
    def main():
        global key_list
        global value_list
        name = input("What is your name? ")
        bid_price = input("What is your bid price? ")
    
        bid_dictionary[name] = bid_price
    
        other_users = input("Are there other users who want to bid? Enter Yes or No. ").lower()
        if other_users == "yes":
            clear()
            main()
        elif other_users == "no": 
            clear()
            list_sorted = dict(sorted(bid_dictionary.items(), key=lambda item: item[1]))
            key_list = list(list_sorted.keys())
            value_list = list(list_sorted.values())
          
            print(list_sorted, key_list, value_list)
        
            print(f"The winner is {key_list[-1]} with a bid of ${value_list[-1]}.")      
    
    main()
                      

Advertisement

Answer

list_sorted = dict(sorted(bid_dictionary.items(), key=lambda item: item[1]))

you are sorting prices as strings here (item[1] is a string). “5” comes last in terms of dictionary order (how strings are compared).

you’ll need to convert the price into integers before comparing

try this:

list_sorted = dict(sorted(bid_dictionary.items(), key=lambda item: int(item[1])))
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement