遍历输入列表向空字典动态添加新键,混合类型列表报KeyError如何解决
问题原因
你的代码中判断条件存在逻辑错误:你需要判断当前遍历元素是否已经存放在目标字典di中,而非判断是否在原列表stuff中。
由于你遍历的所有元素本身就属于stuff,因此if thing not in stuff这个判断永远为假,程序每次都会走else分支,尝试给字典中不存在的键执行+=1操作,自然会抛出KeyError。
你所说的「仅包含数字的列表可以正常运行」,是测试时的代码和本次贴出的代码不一致导致的,比如误将判断条件写为thing not in di,当前贴出的代码无论列表元素是啥类型都会抛出KeyError。
修复方案
- 方案1:直接修正判断条件,将判断范围改为目标字典即可
di = {} stuff = ['sun', 20, 20, 14.3, 'sun', 'Flower'] for thing in stuff: if thing not in di: di[thing] = 1 else: di[thing] += 1 print(di)
- 方案2:使用
dict.get()方法简化逻辑,省略分支判断
di = {} stuff = ['sun', 20, 20, 14.3, 'sun', 'Flower'] for thing in stuff: di[thing] = di.get(thing, 0) + 1 print(di)
- 方案3:直接调用标准库的计数工具
collections.Counter,一步完成统计
from collections import Counter stuff = ['sun', 20, 20, 14.3, 'sun', 'Flower'] di = Counter(stuff) print(dict(di)) # 不需要普通字典的话可以省略转dict操作
内容的提问来源于stack exchange,提问作者Vic
相关产品推荐
相关产品推荐

