Nested dictionary creation with setdefault Is there a better way of creating a nested dictionary than what I'm doing below? The result for the setdefault is because I don't know whether that particular key exists yet or not.
def record_execution_log_action(
        execution_log, region, service, resource, resource_id, resource_action
    ):
        execution_log[&quot;AWS&quot;].setdefault(region, {}).setdefault(service, {}).setdefault(
            resource, []
        ).append(
            {
                &quot;id&quot;: resource_id,
                &quot;action&quot;: resource_action,
                &quot;timestamp&quot;: datetime.datetime.now().strftime(&quot;%Y-%m-%d %H:%M:%S&quot;),
            }
        )
Use a defaultdict like so:
from collections import defaultdict

resource_dict = lambda: defaultdict(list)
service_dict = lambda: defaultdict(resource_dict)
region_dict = lambda: defaultdict(service_dict)
execution_log = defaultdict(region_dict)

execution_log['AWS']['region']['service']['resource'].append({
                &quot;id&quot;: 'resource_id',
                &quot;action&quot;: 'resource_action',
                &quot;timestamp&quot;: &quot;%Y-%m-%d %H:%M:%S&quot;,
            })

execution_log

output:
defaultdict(&lt;function __main__.&lt;lambda&gt;()&gt;,
            {'AWS': defaultdict(&lt;function __main__.&lt;lambda&gt;()&gt;,
                         {'region': defaultdict(&lt;function __main__.&lt;lambda&gt;()&gt;,
                                      {'service': defaultdict(list,
                                                   {'resource': [{'id': 'resource_id',
                                                      'action': 'resource_action',
                                                      'timestamp': '%Y-%m-%d %H:%M:%S'}]})})})})