我正在尝试向python字典添加新的键值寄存器,其中key和key将作为循环中的变量名,下面是我的代码:
def harvestTrendingTopicTweets(twitterAPI, trendingTopics, n):
statuses = {}
for category in trendingTopics:
for trend in trendingTopics[category]:
results = twitterAPI.search.tweets(q=trend, count=n, lang='es')
statuses[category][trend] = results['statuses']
return statuses
trendingTopics
是在这个json之后生成的字典
{
"General": ["EPN","Peña Nieto", "México","PresidenciaMX"],
"Acciones politicas": ["Reforma Fiscal", "Reforma Energética"]
}
到目前为止,我得到了KeyError: u'Acciones politicas'
错误消息,因为这样的键不存在。我怎样才能做到这一点?你知道吗
在为dictionary元素赋值之前,需要确保键确实存在。所以,你可以
这样可以确保,如果没有找到
category
,那么第二个参数将用作默认值。因此,如果字典中不存在当前的category
,则将创建一个新字典。你知道吗你有两个选择。使用^{} :
setdefault
检查键category
,如果不存在,则将statuses[category]
设置为第二个参数,在本例中是一个新的dict
。然后从函数返回,因此[trend]
在statuses
内的字典上操作,不管是新字典还是现有字典或创建^{} :
defaultdict
与dict
类似,但它不是在找不到键时引发KeyError
,而是调用作为参数传递的方法。在本例中,dict()
,它在该键处创建一个新的dict
实例。你知道吗相关问题 更多 >
编程相关推荐