Reputation:
I'm trying to create a dictionary inside a dictionary with one statement. If the key doesn't exist it should be created.
A code-snippet for what I have now:
self.data[self.stringvar1.get()] = { date : (int(self.total.get()), int(self.resources.get())) }
This doesn't create a new key, but overrides the self.data, even if stringvar1 was different. I've tried a few options and couldn't find what I want. Do I have to manually check if the key exists, or is there an easy idiom for this?
Upvotes: 1
Views: 166
Reputation: 235
This is more of an idea than an answer (maybe I can't add comments because I'm a 'new' user).
To merge dictionaries you might try doing something like:
var = dict(dict1.items() + dict2.items())
As for adding the key if it doesn't exist, you might want to check:
setdefault(key[, default])
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
Upvotes: 0
Reputation: 602715
One option is to make self.data
a collections.defaultdict(dict)
. Accessing non-existent keys on this defaultdict
automatically creates a new dictionary for this key, and you can simply use
self.data[self.stringvar1.get()][date] = (
int(self.total.get()), int(self.resources.get()))
Note that a defaultdict
comes with the risk of hiding bugs, since you will never get a KeyError
. An alternative is to use a plain dict
and the setdefault()
method:
self.data.setdefault(self.stringvar1.get(), {})[date] = (
int(self.total.get()), int(self.resources.get()))
Upvotes: 1