[英]How do you check that each entry in a dictionary is not empty in python?
When trying to iterate over a dictionary, I tried to make sure that each value in the dictionary is not None or empty and an error is thrown.在尝试遍历字典时,我尝试确保字典中的每个值都不是 None 或空并且会引发错误。 The code is bellow.
代码如下。
articleSummaries = {}
for techUrlDictionary in [newYorkTimesTechArticles, washingtonPostTechArticles]:
for articleUrl in techUrlDictionary:
if techUrlDictionary[articleUrl][0] is not None:
if len(techUrlDictionary[articleUrl][0]) > 0:
fs = FrequencySummarizer()
summary = fs.extractFeatures(techUrlDictionary[articleUrl],25)
articleSummaries[articleUrl] = {'feature-vector': summary,
'label': 'Tech'}
And the error message looks like this.错误消息如下所示。
----> 5 if techUrlDictionary[articleUrl][0] is not None:
6 if len(techUrlDictionary[articleUrl][0]) > 0:
7 fs = FrequencySummarizer()
TypeError: tuple indices must be integers or slices, not dict
What would be the best way to execute these checks?执行这些检查的最佳方式是什么? So this error is avoided?
所以避免了这个错误?
I can't run your code, and the wording of your question is a little ambiguous.我无法运行您的代码,并且您的问题的措辞有点模棱两可。 As @Zvone said, you're using the url as a dictionary.
正如@Zvone 所说,您正在使用 url 作为字典。
However, are you trying to do something similar like this?但是,您是否正在尝试做类似的事情?
articleSummaries = {}
for techUrlDictionary in [newYorkTimesTechArticles, washingtonPostTechArticles]:
for articleUrl in techUrlDictionary:
if techUrlDictionary[articleUrl][0]:
if len(techUrlDictionary[articleUrl][0]) > 0:
fs = FrequencySummarizer()
summary = fs.extractFeatures(techUrlDictionary[articleUrl],25)
articleSummaries[articleUrl] = {'feature-vector': summary,
'label': 'Tech'}
else:
print("Empty entry")
I'm assuming that each dict
in the list has a key 0
.我假设列表中的每个
dict
都有一个键0
。 Since you are iterating through the list with the dict
s, you can access the dict
s as is:由于您正在使用
dict
遍历列表,因此您可以按原样访问dict
:
articleSummaries = {}
for techUrlDictionary in [newYorkTimesTechArticles, washingtonPostTechArticles]:
for articleUrl in techUrlDictionary:
if articleUrl[0] is not None:
if len(articleUrl[0]) > 0:
fs = FrequencySummarizer()
summary = fs.extractFeatures(articleUrl,25)
articleUrl = {'feature-vector': summary,
'label': 'Tech'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.