trayceetrace trayceetrace - 9 months ago 38
Python Question

How do I add a key (an integer inputted by user) and a value (inputted in a list by user) to a dictionary so I can reference the key later?

I'm writing a program that would allow the user to add new information about a product. The information is stored in a dictionary. I'm having trouble assigning a key to information stored in a list and adding them to the dictionary.

Here's the snippet:

Adds New Product to the existing Product List and view the list

#This is how the input should be stored in the existing dictionary

prodlist = {1:['bread', 3.10, 'Breakfast food'], 2:['cheese', 4.00, \
'Dairy Product'], 3:['onions', 1.65, 'Vegetable'], 4:['milk', 3.10, \
'Dairy Product'], 5:['mandarines', 0.50, 'Citrus fruit']}

#The key is the ID number the Value is the list

products = [] #List to store inputted variables
if prod_id != 0:
prodlist['Last Product Added'] = {prod_id:products}
print "\n\nThis is the updated product list: \n"
print "\t\t Product ID No. : Product Information\n"
return prodlist

It works as is but I don't want to have
['Last Product Added']
as the key, I need
to be the key but I don't know how to do that. All variables are inputted by the user so there's no way to know what the next key would be. What's the simplest way? Thanks.

Answer Source

prodList[prod_id] = products

For what it's worth you have a dictonary and not a list so you might want to reflect that in your naming.