3 ms·
Python has too many ways to do it: >>> state2name2visited = {} >>> state2name2visited.setdefault("PA", {}).setdefault("Joe", []).append("Pittsburgh")
by earthboundkid 5y ago
Python has too many ways to do it:
>>> state2name2visited = {}
>>> state2name2visited.setdefault("PA", {}).setdefault("Joe", []).append("Pittsburgh")
>>> state2name2visited
{'PA': {'Joe': ['Pittsburgh']}}
- abcxjeb284 5y agoIt’s really 2 ways to do it, and the defaultdict way (I believe) would have less allocations in a deeply nested loop (since this version has to create a {} and a [] every time). Also setdefault causes confusion for less experienced users in a way that the defaultdict format does not.