Apr-27-2024, 09:59 PM
(Apr-27-2024, 04:57 PM)Pedroski55 Wrote: Is there a good reason why we should not pass the dictionary we want modified by name?Can do something like this,but think how this solution would look if adding more shopping list.
Then have to make dictionary's global eg clothes_shop_list = {}, hardware_store = {} and add to them.
Also a ordinary class make more sense for this,if not familiar with @dataclass.
class ShoppingList: def __init__(self, name): self.name = name self.items = {} def add_item(self, item_name, quantity): if item_name in self.items: self.items[item_name] += quantity else: self.items[item_name] = quantity def show_list(self): print(f"{self.name} Shopping List:") for item, quantity in self.items.items(): print(f"{quantity} x {item}") print("-" * 25) # Create separate shopping list objects with names clothes_list = ShoppingList("Clothes") electronics_list = ShoppingList("Electronics") # Add items to each shopping list clothes_list.add_item('T-shirt', 5) clothes_list.add_item('Jeans', 2) electronics_list.add_item('USB cable', 3) electronics_list.add_item('Headphones', 1) # Display each shopping list clothes_list.show_list() electronics_list.show_list()
Output:Clothes Shopping List:
5 x T-shirt
2 x Jeans
-------------------------
Electronics Shopping List:
3 x USB cable
1 x Headphones
-------------------------