我得到这个:KeyError: '284882215'
。一世无法通过Google /在StackOverflow上找到任何内容;有人可以帮忙吗?
干杯!
ios_clean = []
ios_already_added = []
for app in ios:
name = app[0]
n_reviews = float(app[5])
print (n_reviews)
if n_reviews == reviews_max[name] and name not in ios_already_added:
ios_clean.append(app)
ios_already_added.append(name)
print (ios_clean)
print (len(ios_already_added))
KeyError Traceback (most recent call last)
<ipython-input-26-e59f5982da23> in <module>
11 n_reviews = float(app[5])
12 print (n_reviews)
---> 13 if n_reviews == reviews_max[name] and name not in ios_already_added:
14 ios_clean.append(app)
15 ios_already_added.append(name)
KeyError: '284882215'
这里的问题是,您正在尝试使用键“ 284882215”访问reviews_max中的项目,并且该项目不存在。
作为解决方案,您可以使用Dict get()安全地查找密钥。
if n_reviews == reviews_max.get(name) and name not in ios_already_added:
Python documentation说:
exception KeyError在现有键集中找不到映射(字典)键时引发。
意思是您尝试访问不存在的密钥。
您可以使用get()方法,如果要绕过KeyError,则该方法将返回找到的值或默认值。这是处理像您这样的用例的标准方法。
dict.get(key, default = None)