The Easy and Intuitive Way!
Creating a shopping list in python can be as easy as it sounds. It’s not only practical but also fun, especially if you have multiple lists to keep track of! …
Creating a shopping list in python can be as easy as it sounds. It’s not only practical but also fun, especially if you have multiple lists to keep track of!
from collections import defaultdict
Next, create an empty dictionary to hold our shopping list items:
Shopping_List = defaultdict(int)
Let’s now add some items to the list by using the ‘update()’ function which updates elements from another dictionary or a mapping (key-value pairs):
Shopping_List.update({"Apple": 10, "Banana": 20, "Cherry": 30})
This line of code will add ‘Apple’, ‘Banana’ and ‘Cherry’ to the shopping list with their respective quantities. We can also increase or decrease the quantity of any item by using the same update function:
Shopping_List["Apple"] += 5 # this will increment Apple in our list by 5 units
To delete items from a defaultdict, we simply use del keyword like this:
del Shopping_List['Banana']
If you want to iterate over the ‘Shopping_List’ and print its contents, then the code is:
for item in Shopping_List.items():
print("Item : {}, Quantity : {}".format(item[0], item[1]))
This concludes the tutorial of creating a shopping list in python using the ‘defaultdict’ class from Python’s built-in collections module.