简体   繁体   中英

remove duplicated items and add similar items in python

i created a dictionary that will take one key and two values, the dictionary will work as follows:

  1. user inputted an item (item will be the key)
  2. user chose how many quantity (value1)
  3. price (value2)

what am trying to approach is I want to add all quantities together, meaning if the user chose the same item with different quantities (eg. user selected pin pasta in the first iteration and quantity, on the second iteration user selected again pink pasta with quantity of 3),Since its the same item, i've to add first iteration quantity '2' with second iteration quantity '3' to be in total 5. The dictionary content would be {'item':[5,3.5]}

In my code I will get n keys with 2 values, the dictionary defined as global..

this is the output of my code:

{'Pink Pasta ': [2, 3.5, 5, 3.5], 'Mushroum Risto ': [3, 5.75, 7, 5.75]}

first iteration user chose pink pasta, quantity = 2
Second iteration user again chose pink pasta, quantity = 3
Third iteration user chose mushroom Risotto, quantity = 3
Fourth iteration again user chose mushroom Risotto, quantity = 4

this is what am seeking for:

{'Pink Pasta ': [5, 3.5], 'Mushroum Risto ': [7, 5.75]}

this is a part of my code,

choise = int(input('Enter dish number: '))
quantity = int(input('Enter how many dishes: '))

item = list(MyDictonary)[choise-1] #extracting the key
DishPrice = float(MyDictonary[item]) #extracting value

if item in Items: #checking if the item is already selected 
   Items[item] += quantity   #if yes, update the new quantity + 
   previous quantity
else:
    Items[item] = quantity

toCart.setdefault(item,[])
if item in Items:
    toCart[item].append(Items[item])
    toCart[item].append(DishPrice)
print(toCart)

You shouldn't be appending to the cart item. You already calculated the total, so just replace the cart item list with the list with the new quantity and the price.

choise = int(input('Enter dish number: '))
quantity = int(input('Enter how many dishes: '))

item = list(MyDictonary)[choise-1] #extracting the key
DishPrice = float(MyDictonary[item]) #extracting value

if item in Items: #checking if the item is already selected 
    Items[item] += quantity   #if yes, update the new quantity + previous quantity
else:
    Items[item] = quantity

toCart[item] = [Items[item], DishPrice]
print(toCart)

There's also no need for the second if item in Items: , since you just created it 2 lines before.

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