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

Python字典添加元组列表触发KeyError问题及正确输出实现求助

解决字典构建时的KeyError与条目覆盖问题

问题根源

  • 执行dictx[c] += [(c2,c1)]时,首次遇到s1这类新键时,字典中还没有该键,Python无法对不存在的键执行追加操作,因此抛出KeyError。
  • 换成dictx[c] = [(c2,c1)]会直接覆盖该键之前的列表值,导致同一键的多个条目仅保留最后一条。

三种可行解决方案

方法1:先判断键是否存在,初始化空列表

先检查键是否在字典中,不存在则创建空列表,再追加元素:

def graph_dict(filename):
    dictx = {}
    with open(filename) as x:
        for i in x:
            c, c1, c2 = i.split()
            if c not in dictx:
                dictx[c] = []
            dictx[c].append((c2, c1))
        return dictx

方法2:使用字典setdefault()方法

setdefault()会自动检查键是否存在,不存在则设置默认空列表,直接返回对应值后追加元素:

def graph_dict(filename):
    dictx = {}
    with open(filename) as x:
        for i in x:
            c, c1, c2 = i.split()
            dictx.setdefault(c, []).append((c2, c1))
        return dictx

方法3:使用collections.defaultdict

defaultdict可指定默认值类型,访问不存在的键时会自动创建对应类型的默认值(此处为列表):

from collections import defaultdict

def graph_dict(filename):
    dictx = defaultdict(list)
    with open(filename) as x:
        for i in x:
            c, c1, c2 = i.split()
            dictx[c].append((c2, c1))
    # 如需转为普通字典,用dict(dictx)
    return dict(dictx)

以上三种方法运行后,均可得到预期输出:

{'s1': [('s2', '10'), ('s3', '14')], 's2': [('s3', '12')], 's3': [('s1', '25')]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:10:28