从变量向python字典添加新键?
我正在尝试向python字典添加新的键值寄存器,其中key和key将作为循环中的变量名,下面是我的代码:从变量向python字典添加新键?,python,dictionary,Python,Dictionary,我正在尝试向python字典添加新的键值寄存器,其中key和key将作为循环中的变量名,下面是我的代码: def harvestTrendingTopicTweets(twitterAPI, trendingTopics, n): statuses = {} for category in trendingTopics: for trend in trendingTopics[category]: results = twitterAPI.
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'
错误消息,因为这样的密钥不存在。我如何才能做到这一点?您有两个选择。或使用:
setdefault
检查键category
,如果不存在,则将statuses[category]
设置为第二个参数,在本例中为新的dict
。然后从函数返回,因此[trend]
在状态
中的字典上操作,无论是新的还是现有的
或创建一个:
defaultdict
类似于dict
,但当找不到键时,它会调用作为参数传递的方法,而不是引发KeyError
s。在这种情况下,dict()
将在该键处创建一个新的dict
实例。在为字典元素赋值之前,需要确保该键实际存在。那么,你能做什么
statuses.setdefault(category, {})[trend] = results['statuses']
这样可以确保,如果未找到
类别
,则第二个参数将用作默认值。因此,如果词典中不存在当前的类别
,将创建一个新词典。在status=defaultdict(dict)
中的dict
是什么意思?
from collections import defaultdict
...
statuses = defaultdict(dict)
statuses.setdefault(category, {})[trend] = results['statuses']