如何创建一个我可以在整个程序中访问的字典?

时间:2015-10-29 21:37:38

标签: python function dictionary

我正在创建一个地址簿程序,并且需要一个我可以添加的字典,编辑和删除,以及pickle。什么是创建它的最佳方式,以便所有功能都可以访问它?我目前在插件功能中有字典,但是如果我将字典调用到另一个函数那么它是否会重置?

到目前为止我的代码(不包括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

1 个答案:

答案 0 :(得分:0)

尝试使用列表。每个变量的一个列表,因为如果您尝试将它们存储为元组,然后将它们添加到主列表中,您将无法或者很难对它们进行充电和编辑。以下是存储数据的示例:

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输入它,长度函数返回3,因此您知道johns数据的存储位置,如果您要添加更多数据,它将会累积起来。

这是一个将其从列表中取出并进行编辑的示例:

print nameList[john_index]
print emailList[john_index]

emailList[john_index] = new_value

我希望你明白:)