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?
One option is to make
self.dataacollections.defaultdict(dict). Accessing non-existent keys on thisdefaultdictautomatically creates a new dictionary for this key, and you can simply useNote that a
defaultdictcomes with the risk of hiding bugs, since you will never get aKeyError. An alternative is to use a plaindictand thesetdefault()method: