c = defaultdict(lambda: 42)
b = defaultdict(lambda: c)
a = defaultdict(lambda: b)
a["a"]["b"]["c"] # --> 42 c = defaultdict(lambda: 42)
b = defaultdict(lambda: c)
a = defaultdict(lambda: b)
a["a"]["b"]["c"] # --> 42Also d["a"] and d["a"]["b"] aren't 42.
d["a"]["b"]["c"] == (d["a"]["b"])["c"]
d = magicdict()
is42 = d["foo"]["bar"]["baz"]
# -> You can read any path and get a default if it doesn't exist.
d["hello"]["world"] = 420
# -> You can set any path and d will then contain { "hello": { "world": 420 }
People use things like jmespath to do this but the fundamental issue is that __getitem__ isn't None safe when you want nested dicts. It's a godsend when dealing with JSON.I feel like we're maybe too in the weeds, I should have just said "now have two expressions in your lambda."
# One
a = d["a"]["b"]["c"]
# Two
a = d["a"]["b"]
b = a["c"]I have a hard time understanding any use case outside of such mocking.