从变量向python字典添加新键?

2024-09-29 17:22:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试向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'错误消息,因为这样的键不存在。我怎样才能做到这一点?你知道吗


Tags: keyinfor字典trendresults寄存器键值
2条回答

在为dictionary元素赋值之前,需要确保键确实存在。所以,你可以

statuses.setdefault(category, {})[trend] = results['statuses']

这样可以确保,如果没有找到category,那么第二个参数将用作默认值。因此,如果字典中不存在当前的category,则将创建一个新字典。你知道吗

你有两个选择。使用^{}

statuses.setdefault(category, {})[trend] = results['statuses']

setdefault检查键category,如果不存在,则将statuses[category]设置为第二个参数,在本例中是一个新的dict。然后从函数返回,因此[trend]statuses内的字典上操作,不管是新字典还是现有字典


或创建^{}

from collections import defaultdict
...
statuses = defaultdict(dict)

defaultdictdict类似,但它不是在找不到键时引发KeyError,而是调用作为参数传递的方法。在本例中,dict(),它在该键处创建一个新的dict实例。你知道吗

相关问题 更多 >

    热门问题