+ 1

Appending a dictionary with items from a list

Hey guys, i have a short question: Let's say i have a Dictionary filled with fruits and their quantity, and a list filled with fruits. Now i want to add the fruits from the list to the dictionary, but i have a problem regarding the quantity. For example i have Inventory = {Apple:1, Banana:1, Pineapple:2} List = [Strawberry,Banana, Banana, Orange] And this is my code so far def addToInventory(inventory,addedItems): for k in addedItems: inventory.setdefault(k,1) I have problems with guessing how to increase the quantity of already existing fruits in inventory. Hope you guys can help me out.

13th Apr 2017, 3:28 PM
Marco
2 Answers
+ 1
inventory = {'Apple': 1, 'Banana': 1, 'Pineapple': 2} fruits = ['Strawberry', 'Banana', 'Banana', 'Orange'] print(inventory) # {'Pineapple': 2, 'Apple': 1, 'Banana': 1} def add_to_basket(basket, stuff): for element in stuff: if element in basket.keys(): basket[element] += 1 else: basket[element] = 1 add_to_basket(inventory, fruits) print(inventory) # {'Pineapple': 2, 'Orange': 1, 'Apple': 1, 'Banana': 3, 'Strawberry': 1} This looks so awful in a non-monospaced font :\
13th Apr 2017, 3:45 PM
Klaus-Dieter Warzecha
Klaus-Dieter Warzecha - avatar
+ 2
Awesome! Thank you very much!
13th Apr 2017, 3:48 PM
Marco