Python Forum
Better way to create nested dictionary with defaultdict()
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Better way to create nested dictionary with defaultdict()
#1
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.
Reply


Messages In This Thread
Better way to create nested dictionary with defaultdict() - by x2mlh - Nov-29-2017, 08:59 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  need to compare 2 values in a nested dictionary jss 2 1,686 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  Create new dictionary angus1964 6 3,452 May-08-2022, 12:43 PM
Last Post: snippsat
  Create new dictionary angus1964 2 1,830 May-06-2022, 02:14 PM
Last Post: deanhystad
  Nested dictionary acting strange Pedroski55 2 2,923 May-13-2021, 10:37 PM
Last Post: Pedroski55
  format the output from a nested dictionary. nostradamus64 9 6,803 May-03-2021, 04:45 PM
Last Post: nostradamus64
Lightbulb Python Nested Dictionary michaelserra 2 3,728 Apr-18-2021, 07:54 AM
Last Post: michaelserra
  How to make this function general to create binary numbers? (many nested for loops) dospina 4 6,219 Jun-24-2020, 04:05 AM
Last Post: deanhystad
  nested dictionary rkpython 7 4,469 May-29-2020, 11:13 AM
Last Post: rkpython
  Nested Dictionary/List tonybrown3 5 4,224 May-08-2020, 01:27 AM
Last Post: tonybrown3
  Help: for loop with dictionary and nested lists mart79 1 2,382 Apr-12-2020, 02:52 PM
Last Post: TomToad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020