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["AWS"].setdefault(region, {}).setdefault(service, {}).setdefault(
            resource, []
                "id": resource_id,
                "action": resource_action,
                "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
  • \$\begingroup\$ You can used a defaultdict from collections module instead, it automatically creates the default( this can be a list) if the key is not found. \$\endgroup\$ Dec 8, 2020 at 0:25
  • 1
    \$\begingroup\$ I've created about defaultdict but I don't get how to use it for my nested use case properly. Could you give an example? \$\endgroup\$
    – mlevit
    Dec 8, 2020 at 0:45

1 Answer 1


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)

                "id": 'resource_id',
                "action": 'resource_action',
                "timestamp": "%Y-%m-%d %H:%M:%S",



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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.