In bash I can use mkdir
's -p
flag to create a directory that is several directories deep without having to check for the existence of all of its ancestor directories, and create them if needed; it will create any nonexistent parent directories along the way. rm -rf a; mkdir -p a/b/c/d/e/f
will create a
, and then b
inside it, and then c
inside b
, and so on, all the way to f
.
In Python I want to be able to do something similar with dictionaries:
nested_dict = dict()
nested_dict["a"]["b"]["c"]["d"]["e"] = "f"
collections.defaultdict
will give me one level of 'forgiveness' if a key does not exist (e.g. if not "a" in nested_dict.keys(): nested_dict["a"]["b"] = "something"
will not raise an Exception if nested_dict is a defaultdict(dict) but not an arbitrarily deep level. Is there currently a nice way of doing such a thing in Python?