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

Python如何合并两个字典 实现患者信息与医疗记录关联

关联患者与医疗记录实现方案

你当前代码的核心问题是患者数据、医疗记录数据分别存在两个独立列表中,没有共通的关联标识,无法完成匹配绑定。实现关联只需要做两处核心调整:

  • 给每个患者分配全局唯一的ID标识,同时在患者字典中预留medical_records空列表,专门存储该患者的所有就诊记录
  • 录入每条医疗记录前,先展示所有已录入患者的列表,让用户输入对应患者的ID完成归属选择,录入的记录直接追加到对应患者的medical_records列表中即可,不需要单独维护全局独立的医疗记录列表。

完整修改后代码

info_patients = []
patient_id_counter = 1  # 自增唯一ID,避免重名患者绑定错误

# 患者信息录入模块
while True:
    Name = input("Insert name: ")
    Lastname = input("Insert last name: ")
    Birth = input("Insert date of birth: ")
    Nationality = input("Insert nationality:")

    info_patients.append({
        "PatientID": patient_id_counter,
        "Name": Name,
        "Lastname": Lastname,
        "Birth": Birth,
        "Nationality": Nationality,
        "medical_records": []  # 预留字段存储该患者的所有医疗记录
    })
    patient_id_counter += 1

    repeat = input("Do you need to add more patient data? (yes / no): ")
    if repeat.lower() == 'no':
        break

# 展示所有已录入患者,供后续绑定医疗记录时选择
print("\n=== All registered patients ===")
for patient in info_patients:
    print(f"ID: {patient['PatientID']} | Name: {patient['Name']} {patient['Lastname']} | DOB: {patient['Birth']}")

# 医疗记录录入模块
while True:
    # 先校验用户选择的患者ID是否有效
    while True:
        try:
            select_id = int(input("\nInput the PatientID to bind this medical record: "))
            target_patient = next((p for p in info_patients if p["PatientID"] == select_id), None)
            if target_patient:
                break
            print("Invalid PatientID, please check the list above and try again.")
        except ValueError:
            print("Please input a valid number for PatientID.")

    # 录入当前医疗记录详情
    Date = input("Insert date of treatment: ")
    Reason = input("Insert reason of treatment: ")
    Doctor = input("Insert doctor in charge of treatment: ")
    Remark = input("Insert any remarks:")

    # 将记录直接追加到对应患者的医疗记录列表,完成绑定
    target_patient["medical_records"].append({
        "Date": Date,
        "Reason": Reason,
        "Doctor": Doctor,
        "Remark": Remark
    })

    repeat = input("Do you need to add more medical records? (yes / no): ")
    if repeat.lower() == 'no':
        break

# 打印绑定完成的全量数据做验证
print("\n=== Final bound data ===")
for patient in info_patients:
    print(f"\nPatient {patient['PatientID']}: {patient['Name']} {patient['Lastname']}")
    print(f"Basic info: DOB {patient['Birth']}, Nationality {patient['Nationality']}")
    print("Medical records:")
    if not patient["medical_records"]:
        print("  No related records")
        continue
    for idx, record in enumerate(patient["medical_records"], 1):
        print(f"  Record {idx}: Date {record['Date']}, Attending Doctor {record['Doctor']}, Reason {record['Reason']}, Remark {record['Remark']}")

补充说明

  • 用自增数字作为患者唯一ID,比直接用姓名做关联键更可靠,不会因为重名导致记录绑定错误
  • 原代码中判断用户是否继续输入的逻辑,可以直接用.lower()方法把输入转成小写,不需要单独判断大写NO的场景
  • 如果后续业务需要单独维护全局医疗记录列表,只需要在每条医疗记录字典中增加PatientID字段存储归属患者的ID,查询时通过ID做匹配即可,练习场景下直接将记录嵌套在患者字典中的写法更简单易维护
  • 后续如果需要给已录入的老患者补录记录,不需要调整现有结构,只需要在录入医疗记录前重新打印患者列表供用户选择ID即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 01:57:24