我有一个包含多个值的键的字典。然后我创建一个临时列表来保存密钥,也就是人名。 但是我无法检索与它们关联的值,或者我不确定如何将键元组保存到一个列表中,我可以在列表中进行迭代,然后打印出用户搜索过的名称及其关联值
contacts = { ("Andy", "Symons", 0): ["0151 231 2635", "", "", "[email protected]"],
("Kirsty", "Lever", 0): ["0151 231 2350", "", "", "[email protected]"]}
#########################
# Function Declarations #
#########################
def searchContacts(contacts):
surname = input("Please enter the contacts surname: ")
firstname = input("Please enter the contacts firstname: ")
if len(contacts) == 0:
print("no contacts found")#if the length of the dictionary equals = 0(checks if there is anything in the dictionary)
else:
templist = list(contacts.keys()) #creates a temporary list of the keys in the dictionary
print(tempdict)
if (firstname, surname, 0) in templist: #searches through the temporary list to find the names
print("Firstname : " + firstname , "Surname : " + surname) #formats names
else:
print("error")#if cannot match name print error
################
# Main Section #
################
searchContacts(contacts)#calls function
输出: 请输入联系人姓氏:Symons 请输入联系人名字:Andy [('安迪', '西蒙斯', 0), ('柯斯蒂', '杠杆', 0)] 名字:安迪姓氏:西蒙斯