【问题标题】:How to create an infinite nested dictionary in Python 3 through user input如何通过用户输入在 Python 3 中创建无限嵌套字典
【发布时间】:2019-01-09 05:54:54
【问题描述】:

我目前正在学习我的第一门 Python 课程,并且没有 CS 方面的背景。我正在开发一个假设程序,该程序结合了我们讨论主题和批判性思维任务中的小问题,以便以对我有意义的方式练习使用代码(我是一名公关人员和摄影师)。目前,该程序是一个客户数据库,供公关人员添加客户信息、打印完整的客户名单和计算预扣税款。

我正在努力创建一个通过用户输入填充的无限嵌套字典。我在网上搜索过,但找不到满足我假设要求的解决方案。

对于程序的“ADD”分支,我希望能够将新的客户端/信息添加到嵌套字典 (client_info)。该程序向用户询问一系列问题,例如客户 ID、乐队名称、合同结束日期、支付和管理。我希望使用某种循环,以便用户可以将一堆波段添加到 client_info 字典,程序将自动更新并为 client_info 字典中的每个波段创建一个新字典。

我首先用四个波段及其信息填充了 client_info。然后我创建了空字典(为每个空字典分配了数字)并为每个空字典编写了单独的代码(总共 10 个),但这意味着我有很多代码,我想不出一种方法来回收代码精简程序。

我还尝试使用乐队的首字母而不是数字,我认为可能有一种简单的方法来分配客户 ID,但是失败得很惨,我找不到让程序运行的方法。

# Define dictionary for client information
client_info = {1: {'band' : 'colfax_speed_queen','email' :  'csq@colfaxspeedqueen.com', 'contract' : '20190808', 'pay' : int(800), 'mgmt' : 'MGI'},
         2: {'band' : 'the_ghoulies', 'email' : 'tg@theghoulies.com', 'contract' : '20191031', 'pay' : int(250), 'mgmt' : 'DIY'},
         3: {'band' : 'hail_satan', 'email' : 'hs@hailsatan.com', 'contract' : '20190606', 'pay' : int(700), 'mgmt' : 'APG'},
         4: {'band' : 'plastic_daggers', 'email' : 'pd@plasticdaggers.com', 'contract' : '20190420', 'pay' : int(1000), 'mgmt' : 'DIY'}}

# Pretend to create infinite nested dictionary for client information, but ultimately fail
c = 4
while c <= 19:
    c += 1
    client_info[c] = {}

# General greeting
print("Welcome to the client database.")

# Directions to use database
main_menu = str("""You can:
    PRINT your client list.
    ADD a new client to the database.
    Calculate your TAX withholding.""")
print(main_menu, "\nWhat would you like to do?")
access_client = input()

# Add client to database
elif access_client.lower() == 'add':

    while access_client.lower() == 'add':

        # Request user input for client id
        print("\nWhat is the client id?")

        # Update client id
        c = int(input())

        # Request user input for client_info[c]['band']
        print("What is the name of the band?")

        # Update client_info[c]['band']
        client_info[c]['band'] = input()

        # Request user input for client_info[c]['email']
        print("What is " + client_info[c]['band'] + "\'s email address?")

        # Update client_info[c]['email']
        client_info[c]['email'] = input()

        # Request user input for client_info[c]['contract']
        print("When does " + client_info[c]['band'] + "\'s contract end?")

        # Update client_info[c]['contract']
        client_info[c]['contract'] = int(input())

        # Request user input for client_info[c]['pay']
        print("What is your payment from " + client_info[c]['band'] + "?")

        # Update client_info[c]['pay']
        client_info[c]['pay'] = int(input())

        # Request user input for client_info[c]['mgmt']
        print("Who is managing " + client_info[c]['band'] + "?")

        # Update client_info[c]['mgmt']
        client_info[c]['mgmt'] = input()

        # Notify user that system has been updated with client information
        print("\nThank you for adding " + client_info[c]['band'] + "\'s information to the client database. The database has been updated.")
        print(client_info[c])
        print(client_info)

        # Ask user to add another client
        print("\nType ADD to add another client. Hit any other key to return to the main menu.")
        add_client = input()
        if add_client.lower() != 'add':
            break
    print(main_menu)

while c

我想我已经接近了,但它没有我希望的那么高效。我会很感激你能给我的任何帮助,因为我是一个完全的菜鸟,不知道我在做什么! 谢谢!

【问题讨论】:

    标签: python python-3.x dictionary nested


    【解决方案1】:

    与其为您尚未输入的客户预先填充空的内部词典,不如在您收集有关新客户的信息之前根据需要创建每个词典。

    您的程序可以自动计算新的客户 ID 号,使用诸如 len(client_info)len(client_info) + 1 之类的东西来根据您已有的记录数获得一个新号码。这是一个非常简短的示例,其中包含非常简化的客户记录:

    client_info = {} # start empty
    
    while True:
        new_client = {}
        name = input("what is the band's name? ")
        new_client['name'] = name
        new_client_id = len(client_info) # starts at zero, add 1 if you want the IDs to start at 1
        client_info[new_client_id] = new_client
    
        print("client added, client_info is now", client_info)
    

    如果您从不从中删除客户端,您也可以考虑为数据结构的顶层使用列表。您只需将 append 记录添加到客户列表中,而不是生成 ID 并使用它进行索引来分配新的客户记录。 ID 将是隐含的,因为客户端最终在列表中的位置。

    【讨论】:

    • 感谢您的帮助!我尝试了一个不同的任务并且它成功了,但是对于那种情况,我开始使用一个空字典。我将要搞乱这个假设的程序并创建一些函数,因为这就是我们本周在我的课程中要学习的内容。我很想知道将这种格式与函数一起使用将如何有助于程序的流程。再次感谢您的详细解答!
    【解决方案2】:

    您可以考虑执行以下原始示例:

    ids = client_info.keys()
    next_c = max(ids) + 1
    
    fields = ['band', 'email', 'contract', 'pay', 'mgmt']
    
    for field in fields:
        print("Enter ", field)
        client_info[next_c][field] = input()
    

    基本思想是找到下一个 c 用作 id 寻找最大实际 id + 1。 这允许避免使用已使用的 id,但如果最后一个被删除则不会。为避免重复使用已使用的 id 而不是删除对象,请将其设置为 None(例如):

    client_info = {1: None, .....}
    

    声明您需要在列表中填充的字段,以便您可以对其进行迭代并保持代码 DRY。


    这只是进一步定制的起点。 例如,自定义答案:
    fields_2 = {'band': 'What is the name of the band?', 'email': 'What is the band email address?', 'contract':'When does contract ends?', 'pay':'What is your payment from the band?', 'mgmt':'Who is managing the band'}
    for field, answer in fields_2.items():
        print(answer)
        # client_info[next_c][field] = input()
    

    所以,用户可以看到:

    # What is the name of the band?
    # What is the band email address?
    # When does contract ends?
    # What is your payment from the band?
    # Who is managing the band?
    

    【讨论】:

    • 感谢您的回复!我仍在对此进行调查并测试不同的建议,因此我会尽快回复您并提供更多反馈。我只是完成所有事情有点慢。
    猜你喜欢
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    相关资源
    最近更新 更多