字典和列表合并难度?

时间:2015-03-19 23:15:40

标签: python-3.x dictionary

我正在使用字典和列表创建信息书。由于列表是元素,我在打印特定元素时遇到问题。

book = {}
print("Welcome to the information book.\n"
    "To add your information, type : 'add'\n"
    "To look up the corporation, type: 'corp'\n"
    "To exit, type: 'end'\n")
menu = input("Enter a menu option stated above: ")
while menu.lower() != 'end':
    if menu.lower() == 'add':
        name = input("Enter your name here: ")
        userID = input("Enter your userID here: ")
        hours = input("Enter the amount of hours worked here: ")
        corporation = input("Enter the corporation name here: ")

        information = []
        information.append(name)
        information.append(hours)
        information.append(corporation)
        book[userID] = information
    elif menu.lower() == 'corp':
        searchFor = input("Enter the name here: ")
        for key in book:
            for element in book[key]:
                if searchFor.lower() == element.lower():
                    print("The corporation name for", searchFor, "is:",
                          information[2])

现在,当我运行并测试我的程序以查找某人的公司名称时,该人的公司名称不正确,但是输入其信息的最后一个人的公司名称。

以下是代码执行时的样子:

Welcome to the information book.
To add your information, type: 'add'
To look up the corporation, type: 'corp'
To exit, type: 'end'

Enter a menu option stated above: add
Enter your name here: James Withson
Enter your userID here: Jwithso23
Enter the amount of hours worked here: 40
Enter the corporation name here: AMC

Enter a menu option stated above: add
Enter your name here: Blake O'boyle
Enter your userID here: Bboyle10
Enter the amount of hours worked here: 35
Enter the corporation name here: GMM

Enter a menu option stated above: corp
Enter the name here: James Withson
The corporation name for James Withson is: GMM
Enter a menu option stated above: 

每次用户添加新人及其信息时,我都尝试将列表连接到新列表,但是当我这样做时的主要问题是我不知道如果用户决定查找某个元素是哪个元素人的公司。有什么建议?感谢

我不能使用其他任何东西作为钥匙,因为可以有相同的名称,公司,工作时间。

需要的任何其他信息,我将很乐意给予。谢谢!

1 个答案:

答案 0 :(得分:0)

替换代码的最后一部分
    elif menu.lower() == 'corp':
        searchFor = input("Enter the name here: ").lower()
        for info in book.values():
            if searchFor == info[0].lower():
                print("The corporation name for", searchFor, "is:", info[2])