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

如何利用列表元素设置字典的键与值?代码生成多字典问题排查

问题分析

你的代码每次循环都重新创建一个新字典覆盖了to_nato变量,而不是往初始的空字典里添加键值对,所以会输出多个独立的单键字典,最终也只会保留文件最后一行的键值对。

修正后的代码
natofile = "nato-alphabet.txt"
to_nato = {}  # 初始化空字典(原注释写错了,不是empty string)
fh = open(natofile)

for line in fh: 
    clean = line.strip()
    if not clean:  # 跳过空行,避免报错
        continue
    lowerl = clean.lower()
    words = lowerl.split()
    to_nato[words[0]] = words[1]  # 往已有字典添加键值对,而非重新赋值

print(to_nato)  # 循环结束后再打印整个字典
fh.close()  # 记得关闭文件
更简洁的安全写法(推荐用with语句自动管理文件)
natofile = "nato-alphabet.txt"
to_nato = {}

with open(natofile) as fh:
    for line in fh:
        clean = line.strip()
        if not clean:
            continue
        key, value = clean.lower().split()
        to_nato[key] = value

print(to_nato)

运行后会输出包含所有字母对应北约音标词的单个字典:

{'a': 'alfa', 'b': 'bravo', 'c': 'charlie', 'd': 'delta', 'e': 'echo', 'f': 'foxtrot', 'g': 'golf', 'h': 'hotel', 'i': 'india'}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:55:15