You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何从含列表的联系人字典查询指定单条记录

问题根因

代码无法正常运行有三个核心问题:

  1. 字典构造写法错误:dict()传入序列初始化时,每个元素必须是(键, 值)格式的二元组,直接把键名和变量平铺传入,初始化阶段就会抛出值错误,根本没法正常存储数据。
  2. 遍历逻辑有缺陷:把"No encontrado"的判断放在循环内部,每遍历一个不匹配的号码就会打印一次提示,号码列表有多长就会打印多少次无效提示,逻辑不符合预期。
  3. 匹配后取值逻辑不全:仅尝试打印了电话号码字段本身,没有遍历字典所有键取对应索引位置的值,自然拿不到整条联系人的完整记录。
修复方案

1. 先修正字典存储结构

你当前用的是列式存储逻辑:所有联系人的同字段值存在同一个列表中,同一个索引位置的元素属于同一个联系人,首先要把字典初始化的写法改对:

# 初始化各字段存储列表,注意不要用id作为变量名,会覆盖Python内置的id()函数
id_list = []
nombres = []
apellidos = []
telefonos = []
correos = []

# 正确构造字典,键为字段名,值为对应字段的所有值列表
contactos = {
    "id": id_list,
    "nombres": nombres,
    "apellidos": apellidos,
    "telefonos": telefonos,
    "correos": correos
}

更推荐后续把存储结构改成行式,即每个联系人是独立字典,统一存在一个大列表中,后续增删改查都会简单很多,参考结构:

contactos = [
    {"id": 1, "nombres": "Juan", "apellidos": "Pérez", "telefonos": "123456789", "correos": "juan@test.com"},
    {"id": 2, "nombres": "María", "apellidos": "López", "telefonos": "987654321", "correos": "maria@test.com"}
]

2. 修正查询逻辑

适配当前列式存储的可运行代码

from colorama import Fore

telefo = input(Fore.LIGHTGREEN_EX + "TELEFONO CONTACTO: " + Fore.RESET)
match_index = None
# 遍历电话号码列表找匹配的索引
for idx, num in enumerate(contactos["telefonos"]):
    if num == telefo:
        match_index = idx
        break

if match_index is not None:
    # 遍历所有字段,取匹配索引对应的值拼成完整联系人信息
    print("查询到联系人信息:")
    for field, value_list in contactos.items():
        print(f"{field}: {value_list[match_index]}")
else:
    print("No encontrado")

适配推荐行式存储的代码(逻辑更简洁)

from colorama import Fore

telefo = input(Fore.LIGHTGREEN_EX + "TELEFONO CONTACTO: " + Fore.RESET)
target_contact = None

for contact in contactos:
    if contact["telefonos"] == telefo:
        target_contact = contact
        break

if target_contact:
    print("查询到联系人信息:")
    for k, v in target_contact.items():
        print(f"{k}: {v}")
else:
    print("No encontrado")

内容的提问来源于stack exchange,提问作者Luiz Villalba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 13:45:31