A shorthand way to create a dictionary key if it does not exist

I have a zoo animal dictionary. I want to put it in a dictionary in a nested dictionary, but get a KeyError because this particular view has not been added to the dictionary.

def add_to_world(self, species, name, zone = 'retreat'):
    self.object_attr[species][name] = {'zone' : zone}

Is there a shortcut to check if this view is in the dictionary and create it if it is not, or should I do it a long way and manually check if this view is added?

+5
source share
3 answers
def add_to_world(self, species, name, zone = 'retreat'):
    self.object_attr.setdefault(species, {})[name] = {'zone' : zone}
+13
source

Auto-visualization of dictionary values ​​can be performed collections.defaultdict.

+9
source

Here is an example of using defaultdict with a dictionary as a value.

>>> from collections import defaultdict
>>> d = defaultdict(dict)
>>> d["species"]["name"] = {"zone": "1"}
>>> d
defaultdict(<type 'dict'>, {'species': {'name': {'zone': '1'}}})
>>>

If you need additional nesting, you will need to make a function to return defaultdict (dict).

def nested_defaultdict():
    return defaultdict(dict)

# Then you can use a dictionary nested to 3 levels
d2 = defaultdict(nested_defaultdict)
d2["species"]["name"]["zone"] = 1
+9
source

All Articles