简体   繁体   English

如何将多个字典添加到主字典中的键? 下面给出示例

[英]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.如何在各自的 category_id 中输入具有“prod_id”和“prod_name”作为键的产品。 When a user requests for category_id_2 he should be able to add 'prod_id' and 'prod_name' in that particular category.当用户请求 category_id_2 时,他应该能够在该特定类别中添加“prod_id”和“prod_name”。

 { 
            {
                'category_id_1':{'prod_id': 'f1a1', 'prod_name': 'apple'},
                                {'prod_id': 'f1a2', 'prod_name': 'banana'},
                                {'prod_id': 'f1a2', 'prod_name': 'banana'}
            }, 
        
            {
                'category_id_2':{'prod_id': 'v1b1', 'prod_name': 'bottle gourd'},
                                {'prod_id': 'v1c1', 'prod_name': 'cauli flower'}
            },
        }

Below is the code of the following!下面是下面的代码!

import sys

inventory = []
final_temp = {}

class Inventory:
    def __init__(self):
        self.temp_category_data = {}

    def add_category(self,category_id):
        self.temp_category_data = {category_id:{}}
        print(self.temp_category_data)

    def add_products(self,category_id,prod_id,prod_name):
        self.temp_category_data = {category_id:{}}
        self.temp_category_data[category_id]['prod_id'] = prod_id
        self.temp_category_data[category_id]['prod_name'] = prod_name
        # final_temp.add(self.temp_category_data)
        inventory.append(self.temp_category_data)

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")

Basically i want to implement a inventory management system!基本上我想实施一个库存管理系统!

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.这将允许您快速搜索类别和产品 ID。

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.如果您发现任何错误或改进领域,请告诉我。

Your code is a bit of a mess logically so I'm offering two approaches你的代码在逻辑上有点乱,所以我提供了两种方法

in add_category changeadd_category更改

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并在add_products添加内容的方式从 append 更改为列表,因为它是一个列表

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:如果每个类别的“prod_id”是唯一的,另一种方法将起作用,即仅更改add_products如下:

self.temp_category_data[category_id][prod_id] = prod_name

this will give you a single dictionary which doesnt require you to search through这将为您提供一个不需要您搜索的字典

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'}} Output: {'Food': {'prod_id': 'Meat', 'prod_name': 'Meat'}, 'Fruits': {'prod_id': 'Melon', 'prod_name': 'Melon'}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM