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

如何从指定格式TXT文件生成外层为列标内层为行标的嵌套字典

Python实现TXT内容转指定结构字典

直接使用以下代码即可完成需求,替换代码中的文件路径为你的本地txt文件路径即可运行:

# 初始化结果存储字典
animal_data = {}

# 读取本地txt文件
with open("你的文件路径.txt", "r", encoding="utf-8") as file:
    all_lines = file.readlines()

# 提取第一行列标签作为外层字典的键
col_labels = [item.strip() for item in all_lines[0].split(":") if item.strip()]
# 为每个外层键预创建空内层字典,避免赋值时报KeyError
for label in col_labels:
    animal_data[label] = {}

# 遍历处理后续数据行
for line in all_lines[1:]:
    line_items = [item.strip() for item in line.split(":") if item.strip()]
    current_attr = line_items[0]
    # 只处理需要的Size、Height两个属性,跳过其他行
    if current_attr not in ("Size", "Height"):
        continue
    # 为每个动物填充对应属性值
    for index, value_str in enumerate(line_items[1:]):
        # 先转浮点取整,再转为字符串格式
        processed_value = str(int(float(value_str)))
        animal_data[col_labels[index]][current_attr] = processed_value

效果验证

运行完成后执行print(animal_data['Dog']['Size']),即可得到输出结果10,完全符合要求。

注意说明

内层字典键创建报错通常是因为没有提前为外层键初始化空的内层字典,直接赋值会触发KeyError,上述代码中提前对每个列标签预创建了空字典,已经规避了该问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:54:00