【问题标题】:Adding new keys to a python dictionary from variables?从变量向python字典添加新键?
【发布时间】:2014-02-06 20:12:16
【问题描述】:

我正在尝试将新的键-键-值寄存器添加到 python 字典中,其中键和键将作为循环中的变量名,这是我的代码:

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' 错误消息,因为这样的密钥不存在。我怎样才能做到这一点?

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    你有两个选择。要么使用dict.setdefault:

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

    setdefault 检查密钥 category,如果不存在,则将 statuses[category] 设置为第二个参数,在本例中为新的 dict。然后从函数中返回,所以[trend]statuses里面的字典进行操作,不管是新的还是存在的


    或者创建一个defaultdict:

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

    defaultdict 类似于dict,但不是在找不到键时引发KeyErrors,而是调用作为参数传递的方法。在这种情况下,dict() 在该键处创建一个新的 dict 实例。

    【讨论】:

    • dict 中的 statuses = defaultdict(dict) 是什么意思?
    【解决方案2】:

    在为字典元素赋值之前,您需要确保键确实存在。所以,你可以这样做

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-27
      • 2010-11-04
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 2010-11-04
      相关资源
      最近更新 更多