1
\$\begingroup\$

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"),
 }
 )
asked Dec 7, 2020 at 23:51
\$\endgroup\$
2
  • \$\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\$ Commented 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\$ Commented Dec 8, 2020 at 0:45

1 Answer 1

2
\$\begingroup\$

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
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.