Skip to content Skip to sidebar Skip to footer

How Can I Add Multiple Dictionaries To A Key Inside A Main Dictionary? Example Is Given Below

How can I input products with 'prod_id' and 'prod_name' as keys in respective category_id. When a user requests for category_id_2 he should be able to add 'prod_id' and 'prod_name'

Solution 1:

I think you can optimize your dictionary to look like this:

{'category A':
    {'Product Id A1' : 'Product Name A1', 
     'Product Id A2' : 'Product Name A2'},

 'category B':
    {'Product Id B1' : 'Product Name B1', 
     'Product Id B2' : 'Product Name B2',
     'Product Id B3' : 'Product Name B3'}
}

This will allow for you to search for the category and product id quickly.

Example of this would be:

{'Fruits': 
    {'Fruit_Id_1': 'Apple', 
     'Fruit_Id_2': 'Banana', 
     'Fruit_Id_3': 'Grapes'},
 'Animals': 
    {'Animal_Id_1': 'Bear',
     'Animal_Id_2': 'Goose'}
}

To create , search, and delete the contents in a nested dictionary, you can use the below code:

cat_dict = {}
def category(opt):
    while True:
        cname = input ('Enter Category Name : ')
        if cname == '': continue
        if opt == '1' and cname in cat_dict:
            print ('Category already exist. Please re-enter')
        elif opt != '1' and cname not in cat_dict:
            print ('Category does not exist. Please re-enter')
        else:
            return cname

def product(cname,opt):
    while True:
        pid = input ('Enter Product Id : ')
        if pid == '': continue
        elif opt == '1': return pid
        elif opt == '2' and pid in cat_dict[cname]:
            print ('Product Id already exist. Please re-enter')
        elif opt != '2' and pid not in cat_dict[cname]:
            print ('Product Id does not exist. Please re-enter')
        else:
            return pid

        
while x:=input("Enter [0] to exit:\n") != '0':
    while True:
        options= input('''Enter
[1] Add Categories
[2] Add Products
[3] Search Categories
[4] Search Products
[5] Delete Category
[6] Delete Product
> ''') 
        if options not in ('1','2','3','4','5','6'):
            print ('Incorrect Entry. Please re-enter\n')
        else:
            break

    #Valid option has been selected

    #Get Category Name
    cat_name = category(options)

    #Get Product Id
    if options in ('1','2','4','6'):
        prod_id = product(cat_name,options)

    #Get Product Name
    if options in ('1','2'):
        while True:
            prod_name = input ('Enter Product Name : ')
            if prod_name != '': break
    
    #Ready to process options 1 thru 6

    #Option 1: Insert Category, Product Id, and Product Name
    if options == '1':
        cat_dict[cat_name] = {prod_id : prod_name}

    #Option 2: Insert Product Id, and Product Name for given Cateogry
    elif options == '2':
        cat_dict[cat_name].update({prod_id : prod_name})

    #Option 3: print out all Product Id and Product Name for requested Category
    elif options == '3':
        print ('All Products with',cat_name, 'are :', cat_dict[cat_name])

    #Option 4: print out the Product Name for requested Category and Product Id
    elif options == '4':
        print ('Product Name for ',prod_id, 'is :', cat_dict[cat_name][prod_id])

    #Option 5: Delete the requested Category and all Product Ids and Product Names
    elif options == '5':
        confirm_delete = cat_dict.pop(cat_name, None)
        if confirm_delete is not None:
            print ('Category :',cat_name,'successfully deleted')

    #Option 6: Delete the Product Id and Product Name within the given Category
    else:
        confirm_delete = cat_dict[cat_name].pop(prod_id, None)
        if confirm_delete is not None:
            print ('Product Id :', prod_id, 'in category:', cat_name,'successfully deleted')
   

I have tested this and it works properly. Let me know if you find any bugs or areas of improvement.


Solution 2:

Your code is a bit of a mess logically so I'm offering two approaches

in add_category change

self.temp_category_data = {category_id:{}}

to be a list:

self.temp_category_data = {category_id:[]}

and in add_products change the way you add stuff from to be append, because its a list

self.temp_category_data[category_id]['prod_id'] = prod_id
self.temp_category_data[category_id]['prod_name'] = prod_name

to

self.temp_category_data[category_id].append({'prod_id':prod_id, 'prod_name':prod_name})

this way you will have a list of dictionaries, but will have to look through it to find any specific one.

Another approach, which will work if "prod_id" are unique per category, is to only change add_products like this:

self.temp_category_data[category_id][prod_id] = prod_name

this will give you a single dictionary which doesnt require you to search through


Solution 3:

Hope you find this helpful.

inventory = {}

class Inventory:
    def add_category(self,category_id):
        inventory[category_id] = {}
        print(inventory)

    def add_products(self,category_id,prod_id,prod_name):
        inventory[category_id]['prod_id'] = prod_id
        inventory[category_id]['prod_name'] = prod_name

x = input("Enter [0] to exit and [1] to continue:\n")
while x != '0':
    if x=='0':
        print("Bye!")
        sys.exit()
    if x=='1':
        y = input("\nEnter \n[1] Add Categories \n\t[1a] Add to existing category \n[2] Add Products\n[3] Search Categories \n[4] Search Products and \n[5] Delete Product\n")
        if y == '1':
            categoryId = input("\nEnter The Category ID: ")
            # categoryName = input("\nEnter The Category Name: ")
        
            inv = Inventory()
            inv.add_category(categoryId)
            print(inventory)
            continue

        if y == '2':
            categoryId = input("\nEnter The Category ID: ")
            prodId = input("\nEnter The Product ID: ")
            prodName = input("\nEnter The Product Name: ")
        
            inv = Inventory()
            inv.add_products(categoryId,prodId,prodName)
        
            print(inventory)
    
        else:
            print("Wrong input Details!!")
            sys.exit()
     x = input("Enter [1] to continue and [0] to exit:\n")

Output:{'Food': {'prod_id': 'Meat', 'prod_name': 'Meat'}, 'Fruits': {'prod_id': 'Melon', 'prod_name': 'Melon'}}


Post a Comment for "How Can I Add Multiple Dictionaries To A Key Inside A Main Dictionary? Example Is Given Below"