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

如何通过用户输入、循环及空格分割构建可序列化的患者字典?

循环输入患者信息并构建可JSON序列化的字典结构

问题需求

需要实现:

  • 每行接收用户输入的患者名、姓、年龄、性别(空格分隔)
  • 输入stop时停止接收
  • 最终生成如下结构的字典,可序列化为JSON文件:
{
  "patients": [
    {
      "first_name": "Jane",
      "last_name": "Doe",
      "age": 33,
      "gender": "f"
    }
  ]
}

现有代码无法实现循环输入和正确构建目标结构:

patients = {}

info = input("Enter first name, last name, age, and gender separated by space. Enter stop to stop:")
 
for key, value in patients.items():
    print('first_name: {}, last_name: {}, age: {}, gender: {}'. format(key, value))

解决代码及说明

下面是完整的实现代码,附带关键步骤解释:

import json

# 初始化目标数据结构:包含patients列表的字典
patients_data = {"patients": []}

while True:
    user_input = input("请输入患者名、姓、年龄、性别(空格分隔),输入stop停止:").strip()
    # 检查是否输入stop,终止循环
    if user_input.lower() == "stop":
        break
    
    # 分割输入内容,获取四个字段
    try:
        first_name, last_name, age_str, gender = user_input.split()
        # 将年龄转换为整数,保证JSON序列化类型正确
        age = int(age_str)
        # 构建单个患者的字典
        patient = {
            "first_name": first_name,
            "last_name": last_name,
            "age": age,
            "gender": gender
        }
        # 添加到patients列表中
        patients_data["patients"].append(patient)
    except ValueError:
        print("输入格式错误,请输入四个空格分隔的内容:名 姓 年龄 性别")

# 打印最终的患者数据
print("\n最终患者数据:")
print(json.dumps(patients_data, indent=2))

# 可选:将数据序列化为JSON文件
with open("patients.json", "w") as f:
    json.dump(patients_data, f, indent=2)
print("数据已保存到patients.json文件")

关键步骤说明

  • 数据结构初始化:用{"patients": []}替代空字典,完全匹配目标结构,patients是存储单个患者字典的列表
  • 循环输入控制:使用while True无限循环,输入stop时执行break终止循环,实现持续接收输入的需求
  • 输入处理:
    • 用split()分割输入字符串,提取四个字段
    • 把年龄字符串转为整数,避免JSON序列化时出现字符串类型的年龄
    • 用try-except捕获输入格式错误(比如字段数量不对、年龄不是数字),给用户明确提示
  • JSON序列化:使用json模块的dump方法将数据写入文件,indent=2让JSON内容排版更易读

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:29:54