Princey
Princey

Reputation: 1

Sorting a user inputted list

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.

Upvotes: 0

Views: 36

Answers (1)

Daweo
Daweo

Reputation: 36540

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)

Upvotes: 1

Related Questions