Creating A User Friendly Inventory Using Python Dictionaries
While I was reviewing chapter 5 of Automate the Boring Stuff, I learned about using Dictionaries in Python. One of the fun exercises demonstrated by the book was using Python’s Dictionary functionality to create a database for a list of supplies for a picnic. The fun part was that we got to write the code in such a way that you are essentially having a ‘conversation’ with the program to enter in the supplies and then it prints out the list nicely. Take a look at the gif below to see a quick demonstration.
The thing is, once I exit out of the interactive shell, everything I entered will be deleted…or will it?
A quick google of this issue brought me to this article, where I learned about the pickle module. Thanks to this module, adding a couple lines of code will save your dictionary to a file and a couple more lines of code will let you retrieve the dictionary at a later point!
What that means is: now we have the tools to create a user-friendly way of entering data, a aesthetically pleasing way to display it, a way to recall all this hard work at a later date and add to it if we want to!
The way I executed on this was by creating two files.
Here is an explanation of the code for both files:
create picnic.py
Here is the code:
import pickle #so we can save the file
picnic = {} #creating a blank dictionary
while True:
print(f"Add a supply to the picnic list!(press Enter when list is complete)")
supply = input()
## This part is to close out the program once input is complete
if supply == '':
break
## This part prompts you if you enter anything that is already recorded and gives you the option to update inventory amount.
if supply in picnic:
print(f"We have {picnic[supply]} {supply} for the picnic. Do you want to update the number?")
update = input()
if update.lower().startswith('y'):
print(f"Enter the new amount of {supply} now:")
newAmount = input()
picnic[supply] = newAmount
else:
pass
## This part lets you enter in new items and the amount.
else:
print(f"Please enter in the amount of {supply}")
amount = input()
picnic[supply] = amount
print(f"Picnic List is updated.")
## This prints out the list nicely
def printPicnic(itemsDict, leftWidth, rightWidth):
print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
for k, v in itemsDict.items():
print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth))
printPicnic(picnic, 13, 10)
## This saves all your hard work into a file called 'picnic_data.pkl'
with open('picnic_data.pkl', 'wb') as f:
pickle.dump(picnic, f)
print("Picnic items saved as a file.")
retrieve picnic.py
Here is the code:
import pickle #so we can retreive the file
## This allows you to retrieve the file'
with open('picnic_data.pkl', 'rb') as f:
picnic = pickle.load(f)
## This is the same code from 'create picnic.py' to format the list nicely
def printPicnic(itemsDict, leftWidth, rightWidth):
print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
for k, v in itemsDict.items():
print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth))
printPicnic(picnic, 13, 10)
## This is mostly the same code from 'create picnic.py' to allow you to edit
## the list, except the first prompt that asks you if you want to make any edits
print(f"Do you want to add additional supplies to the list? (y/n)")
addition = input()
if addition.lower().startswith('y'):
while True:
print(f"Add a supply to the picnic list!(press Enter when list is complete)")
supply = input()
if supply == '':
break
if supply in picnic:
print(f"We have {picnic[supply]} {supply} for the picnic. Do you want to update the number?")
update = input()
if update.lower().startswith('y'):
print(f"Enter the new amount of {supply} now:")
newAmount = input()
picnic[supply] = newAmount
else:
pass
else:
print(f"Please enter in the amount of {supply}")
amount = input()
picnic[supply] = amount
print(f"Picnic List is updated.")print(f"Here is your final picnic list:")
printPicnic(picnic, 13, 10)
So, there you have it! Not the most straightforward way to create a database, but it still is pretty fun!
Are you working on a Python project that involves Dictionaries? I would love to hear about it.
Also, do you struggle to keep up with everything I’m up to? Now you can subscribe to my free substack 5 on the 9 – where you’ll get an email on the 9th of every month with 5 updates from me!