\$\begingroup\$
\$\endgroup\$
2
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, []
).append(
{
"id": resource_id,
"action": resource_action,
"timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
}
)
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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({
"id": 'resource_id',
"action": 'resource_action',
"timestamp": "%Y-%m-%d %H:%M:%S",
})
execution_log
output:
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'}]})})})})
answered Dec 8, 2020 at 4:06
lang-py
defaultdict
fromcollections
module instead, it automatically creates the default( this can be alist
) if thekey
is not found. \$\endgroup\$defaultdict
but I don't get how to use it for my nested use case properly. Could you give an example? \$\endgroup\$