joaquin
joaquin

Reputation: 85653

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

Upvotes: 3

Views: 677

Answers (2)

Dan D.
Dan D.

Reputation: 74655

try:

partial = defaultdict(lambda: defaultdict(list))

Upvotes: 6

Gareth Rees
Gareth Rees

Reputation: 65854

partial = defaultdict(lambda: defaultdict(list))

Upvotes: 6

Related Questions