Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 812
joaquin Avatar asked Jan 30 '26 05:01

joaquin


1 Answers

partial = defaultdict(lambda: defaultdict(list))
like image 173
Gareth Rees Avatar answered Jan 31 '26 21:01

Gareth Rees



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!