我想在空字典通过/读取我的列表时将新键添加到它。
当我使用仅包含数字的列表时,我得到了它。但是,如果我尝试使用包含字符串和数字的列表进行此操作,我会得到列表中第一个字符串的 KeyError。
谁能告诉我这是为什么,或者我该如何解决?
di = {}
stuff = ['sun', 20, 20, 14.3, 'sun', 'Flower']
for thing in stuff:
if thing not in stuff:
di[thing] = 1
else:
di[thing] += 1
print(di)
最佳答案
您正在检查列表中是否存在 thing
,而不是字典中。
di = {}
stuff = ['sun', 20, 20, 14.3, 'sun', 'Flower']
for thing in stuff: # error was here
if thing not in di:
di[thing] = 1
else:
di[thing] += 1
print(di)
你知道collections.Counter
吗? ? Counter
是 dict
的子类,可以为您进行计数。
from collections import Counter
di = Counter(stuff)
print(di)
如果您仍在学习,您的方法很好,但使用 Counter
是可行的方法。
https://stackoverflow.com/questions/69688380/