Python-字典初始化

时间:2017-03-26 21:42:23

标签: python python-3.x dictionary

我需要有三个名字和电子邮件地址才能开始使用。我曾试图使用emailaddress = {"Drew": drew@myemail.com, "Lucie": lucie@snailmail.com, "Brodie": brodie@geemail.com},但它会给我这个:

追踪(最近一次呼叫最后一次):

文件“C:/ Users / Drew / Documents / CIT 144 / Email dictionary.py”,第17行,   

emailaddress = {“Drew”:drew@myemail.com,“露西”:lucie@snailmail.com,

NameError:名称'drew'未定义

该程序将与emailaddress = {}一起使用,但如果它有键/值,则会出错。我是Python和编程的新手,所以任何帮助或解释都非常受欢迎!!!

## This program keeps names and email addresses
# in a dictionary called emailaddress as key-value pairs.
# The program should initialize the dictionary with three
# people/email addresses. Then program should display the
# menu and loop until 5 is selected
##

def displayMenu():
    print()
    print("1) Look up email address")
    print("2) Add a name and email address")
    print("3) Change email address")
    print("4) Delete name and email address")
    print("5) End program")
    print()

emailaddress = {}
choice = 0
displayMenu()
while choice != 5:
    choice = int(input("Enter your selection (1-5): "))

    if choice == 1:
        print("Look up email address:")
        name = input("Name: ")
        if name in emailaddress:
            print("The email address is", emailaddress[name])
        else:
            print(name, "was not found")
    elif choice == 2:
        print("Add a name and email address")
        name = input("Name: ")
        email = input("Email: ")
        emailaddress[name] = email
    elif choice == 3:
        print("Change email address")
        name = input("Name: ")
        if name in emailaddress:
            email = input("Enter the new address: ")
            emailaddress[name] = email
        else:
            print(name, "was not found")
    elif choice == 4:
        print("Delete name and email address")
        name = input("Name: ")
        if name in emailaddress:
            del emailaddress[name]
        else:
            print(name, "was not found")          
    elif choice != 5:
        print("Enter a valid selection")
        displayMenu()

2 个答案:

答案 0 :(得分:1)

你只是声明你的字符串没有引号,让python尝试解释它们并失败。

emailaddress = {"Drew": "drew@myemail.com", "Lucie": "lucie@snailmail.com", "Brodie": "brodie@geemail.com"}

会奏效。请注意电子邮件附近的引号

答案 1 :(得分:0)

emailaddress = {"Drew": drew@myemail.com, "Lucie": lucie@snailmail.com, 
"Brodie": brodie@geemail.com}

drew@myemail.com不是字符串。它应该在引文中。