首页 > 解决方案 > 如何让用户创建任意数量的字典

问题描述

我应该创建一个费用跟踪器,其中包含数据字段“类别、供应商和金额”。用户输入他们想要的类别并将其转换为字典。然后他们输入供应商作为键和金额作为值。我能够做到这一点,但用户应该能够创建他们想要的任意数量的类别。在我的代码中,它只创建一个字典,当它循环回来时,它会忘记前一个字典并创建一个新字典。对不起我的措辞,因为我对 python 很陌生。

while True:
    user_category = input("What category do you want to enter? ")
    user_category = dict()
    user_vendor = int(input("How many vendors are you entering under this category? "))
    data_maker (user_category, user_vendor)

def data_maker (category, vendor_number):
    for i in range(vendor_number):
        vendor = input('Please enter a vendor name: ')
        transactions = [float(i) for i in input("Enter in each transaction for vendor entered 
        previously (seperated by spaces) (For example: 90 70.15 87.50): ").split(" ")]    
        category[vendor] = transactions
    print(category)

下面是输出

{'autoparts': [90.0, 91.5, 45.9]}

正如您在上面看到的,用户创建了类别并使其成为字典。然后用户输入他们将在该类别下放置多少供应商。然后通过函数“data_maker”将供应商和交易添加到字典中。

这是我的问题开始的地方......

user_choices = input("If you would like to check total expense for a specific category type 'specific category'. If you would like to continue type 'continue'. If you would like to exit type 'exit'. ")
    if user_choices == "specific category":
        user_category_choice = input("what category do you want to check? ")
        specific_category_total (user_category_choice)
    if user_choices == "exit":
        break;

我想知道如何创建它,以便用户可以创建任意数量的类别,然后键入类别的名称,以便直接上面的代码可以获得它的所有费用。如果有人能把我推向正确的方向,我将不胜感激。我不知道我是不是很不幸,只是无法在任何地方找到答案,或者我是否以错误的方式解决这个问题。

标签: pythondictionary

解决方案


这里有一些问题。首先,您从用户那里获得一个值user_category,然后立即通过为该变量分配一个新值将其丢弃。下一个问题是您没有存储所有类别字典的空间。

以下是修改主循环的方法:

all_dicts = {} # Make global storage for all dictionaries
while True:
    user_category = input("What category do you want to enter? ")
    # Make new category dictionary, if not already in global storage
    category_dict = all_dicts.setdefault(user_category, {})
    user_vendor = int(input("How many vendors are you entering under this category? "))
    # Use the dictionary you made/retrieved in data_maker()
    data_maker (category_dict, user_vendor)

这里的关键是将所有类别字典存储在字典中(按类别名称索引)。setdefault字典方法允许您使用已经与键关联的对象(如果存在),或者创建一个新对象和关联,并使用创建的对象。


推荐阅读