0
purchases = {}

for i in range (5):
    product = input("Enter product name")
    price = int(input("Enter a product price"))
    purchases[product] = price

sortedpurch = sorted(purchases.items())
    
print(purchases)
print(lowestpricefind)
print(sortedpurch)

I'm having trouble getting my list to sort from highest to lowest number.

It loops to add five item names and their corresponding price. Those products/prices are contained in 'purchases'. I can print purchases fine:

Output:

Enter product nameProduct 1
Enter a product price15
Enter product nameProduct 2
Enter a product price10
Enter product nameProduct 3
Enter a product price20
Enter product nameProduct 4
Enter a product price50
Enter product nameProduct 5
Enter a product price30

{'Product 1': 15, 'Product 2': 10, 'Product 3': 20, 'Product 4': 50, 'Product 5': 30}
('Product 2', 10)
[('Product 1', 15), ('Product 2', 10), ('Product 3', 20), ('Product 4', 50), ('Product 5', 30)]

But at the bottom here, it is not sorting as I hoped it would.

1 Answer 1

1

When you do

sortedpurch = sorted(purchases.items())

it sorts by keys (product names), you need to provide function to sorted which will be used to get value to comparison

sortedpurch = sorted(purchases.items(),key=lambda x:x[1])

this takes second part of each pair i.e. price and sort it in ascending order, to get descending request reversing of orders as follows

sortedpurch = sorted(purchases.items(),key=lambda x:x[1],reverse=True)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.