I need to loop through some JSON data (company storm data) and create a nested dictionary 4 keys deep with the first 3 keys having values of type dict and the last key having a value of type list that will store integers. I want to avoid KeyErrors so i am using defaultdict(). To avoid AttributeErrors when assigning to the list i have come up with 2 solutions. The first uses nested defaultdict() passing a list to the final defaultdict() call:
nestedDict = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(list))))
nestedDict[k1][k2][k3][k4].append(someInt)
another uses a recursive function with a try/except clause:
def dict_factory():
return defaultdict(dict_factor)
nestedDict = dict_factory()
try:
nestedDict[k1][k2][k3][k4].append(someInt)
except AttributeError:
nestedDict[k1][k2][k3][k4] = [someInt]
the first solution is certainly shorter but will the embedded defaultdict() produce any issues that i'm not considering. the second solution is wordier but i'm wondering if it is the best way. is one solution recommended over the other?
any assistance would be appreciated.
thanks.
nestedDict = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(list))))
nestedDict[k1][k2][k3][k4].append(someInt)
another uses a recursive function with a try/except clause:
def dict_factory():
return defaultdict(dict_factor)
nestedDict = dict_factory()
try:
nestedDict[k1][k2][k3][k4].append(someInt)
except AttributeError:
nestedDict[k1][k2][k3][k4] = [someInt]
the first solution is certainly shorter but will the embedded defaultdict() produce any issues that i'm not considering. the second solution is wordier but i'm wondering if it is the best way. is one solution recommended over the other?
any assistance would be appreciated.
thanks.