Search code examples
pythondictionarydefaultdict

How to define and fill a dict of dicts of lists


I have to fill a dictionary of the type:

partial[sequence][exp_id] = [item_1, ..., item_n]

this can be done in this way:

partial = defaultdict(dict)

for sequence in sequences:
   for exp_id in exp_ids:
       for item in data:
           partial[sequence].setdefault(eid, []).append(item)

Is there a more effective way? Something like:

partial = defaultdict(defaultdict(list))

for sequence in sequences:
   for exp_id in exp_ids:
       for item in data:
          partial[sequence][exp_id].append(item)

would be perfect but unfortunately doesn't work because defaultdict wants a callable as first argument


Solution

  • partial = defaultdict(lambda: defaultdict(list))