Python字典多值检索问题:如何根据键获取关联多值并输出
问题解决:检索字典中元组键关联的多值列表
我有一个Python字典,键是元组(存储联系人姓名等信息),对应的值是多元素列表(联系方式等)。目前已经用临时列表存储了字典的键,但没法检索这些键对应的多值,也不确定怎么遍历存了键元组的列表,实现输入联系人姓名后输出对应的姓名和关联多值。
原始代码
contacts = { ("Andy", "Symons", 0): ["0151 231 2635", "", "", "a.symons@ljmu.ac.uk"], ("Kirsty", "Lever", 0): ["0151 231 2350", "", "", "K.E.Lever@ljmu.ac.uk"]} ######################### # 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
问题分析
- 代码存在笔误:定义了
templist存储字典键,但打印时用了未定义的tempdict,会触发NameError - 无需将键转成列表再判断,直接在字典中检查键是否存在更高效
- 未实现关联多值的检索与输出逻辑
修正后的代码
contacts = { ("Andy", "Symons", 0): ["0151 231 2635", "", "", "a.symons@ljmu.ac.uk"], ("Kirsty", "Lever", 0): ["0151 231 2350", "", "", "K.E.Lever@ljmu.ac.uk"]} def searchContacts(contacts): # 调整输入提示为中文 surname = input("请输入联系人姓氏: ") firstname = input("请输入联系人名字: ") if not contacts: print("未找到任何联系人") return # 构造目标键元组,和字典中键的结构保持一致 target_key = (firstname, surname, 0) if target_key in contacts: # 获取关联的多值列表 contact_info = contacts[target_key] print(f"名字: {firstname} 姓氏: {surname}") print(f"电话: {contact_info[0]}") print(f"邮箱: {contact_info[3]}") # 可根据需求输出其他字段 else: print("未找到该联系人") searchContacts(contacts)
输出示例
请输入联系人姓氏: Symons 请输入联系人名字: Andy 名字: Andy 姓氏: Symons 电话: 0151 231 2635 邮箱: a.symons@ljmu.ac.uk
关键说明
- 直接利用字典的键查找特性,无需将键转成列表遍历,效率更高
- 找到目标键后,通过
contacts[target_key]直接获取对应的多值列表,按需输出其中元素 - 调整输入输出为中文,格式更贴合使用习惯
内容的提问来源于stack exchange,提问作者Darryl Shields
相关产品推荐
相关产品推荐

