diegoaguilar
diegoaguilar

Reputation: 8376

Adding new keys to a python dictionary from variables?

I'm trying to add new key-key-value registers to a python dictionary where key and key will be taken as variable names in a loop, here is my code:

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 is a dictionary generated after this json

{
    "General": ["EPN","Peña Nieto", "México","PresidenciaMX"],
    "Acciones politicas": ["Reforma Fiscal", "Reforma Energética"]
}

So far I'm getting KeyError: u'Acciones politicas' error message as such key doesn't exist. How can I accomplish this?

Upvotes: 1

Views: 173

Answers (2)

mhlester
mhlester

Reputation: 23251

You have two choices. Either use dict.setdefault:

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

setdefault checks for the key category, and if that doesn't exist, sets statuses[category] to the second argument, in this case a new dict. That is then returned from the function, so [trend] is operated on the dictionary inside statuses, be it the new one or one that existed


Or create a defaultdict:

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

defaultdict is similar to a dict, but instead of raising KeyErrors when a key isn't found, it calls the method passed as argument. In this case, dict() which creates a new dict instance at that key.

Upvotes: 2

thefourtheye
thefourtheye

Reputation: 239653

Before you assign a value to the dictionary elements, you need to make sure that the key actually exists. So, you can do

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

This makes sure that, if the category is not found, then the second parameter will be used as the default value. So, if the current category doesn't exist in the dictionary, a new dictionary will be created.

Upvotes: 1

Related Questions