[英]How to create a dictionary that I can access throughout the program?
我正在创建一个地址簿程序,并且需要有一个字典,我也可以添加,编辑和删除字典以及泡菜。 创建所有功能都可以访问的最佳方法是什么? 我目前在addon函数中有字典,但是如果我将字典调用到另一个函数时,它不会重置吗?
到目前为止,我的代码(不包括menuModule)
def addPerson():
personLastName = input("Enter the last name of "
"the person you want to add: ").lower()
personFirstName = input("Please enter the first name of "
"the person you want to add: ")
localPart = input("Please enter the local part of the email address")
while not localPart.isalnum():
localPart = input("Please enter a valid input, a-z and numbers 0-9: ")
domain = input("Please enter the domain of the email addres: ")
while not domain.isalnum():
domain = input("Please enter a valid input, a-z and numbers 0-9: ")
topLevelDomain = input("Please enter the top level domain, examples: com, net, org: ")
while not topLevelDomain.isalnum() or len(topLevelDomain) > 3:
topLevelDomain = input("Please enter only letters, a-z and not more then 3 characters: ")
personEmail = localPart + "@" + domain + "." + topLevelDomain
personStreetAddress = input("Please enter house number and street of the person you want to add: ")
personCityState = input("Please enter the city, state abbreviation and zipcode of the person you want to add: ")
personPhone = input("Please enter the phone number of the person you want to add: ")
personPhoneStr = personPhone.strip("-")
while not personPhoneStr.isdigit() and not len(personPhoneStr) == 10:
personPhone = input("Error. That is not a valid phone number. Try again: ")
personPhoneStr = personPhone.strip("-")
return personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone
def appendDictionary():
personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone = addPerson()
listX = [personFirstName, personEmail, personStreetAddress, personCityState, personPhone]
addressBook = {personLastName: listX}
print(personFirstName,personLastName, "has been added to the address book!")
print(addressBook)
return addressBook
尝试使用列表。 每个变量都有一个列表,因为如果您尝试将它们存储为元组,然后将它们添加到主列表中,将无法执行,否则将很难对它们进行充电和编辑。 这是存储数据的示例:
nameList.extend(john)
emailList.extend(john@gmail.com.uk)
john_index = len(nameList)
给每个人一个索引,以帮助您归档他们的信息,因此,如果我们的列表看起来像[jane @ live.com,sam @ wenston.com,john @ gmail.com.uk],则johns数据将成为列表中的最后一个,因为我们只是将其输入到列表的第3位,并且length函数返回3,因此您知道johns数据的存储位置,如果要添加更多数据,它会堆积起来。
这是将其从列表中删除并进行编辑的示例:
print nameList[john_index]
print emailList[john_index]
emailList[john_index] = new_value
我希望你明白 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.