I am looking for the fastest way to filter for certain keys from "inner" dictionaries inside lists inside an "outer" dictionary, so kind of a tricky data structure.
The data structure (input) looks like this: All inner dictionaries have the same keys but the lists can have different numbers of dictionaries.
d = {1:[{1:33 ,2:33, 3:33, 4:33}, {1:33 ,2:33, 3:33, 4:33}, {1:33 ,2:33, 3:33, 4:33}],
2:[{1:33 ,2:33, 3:33, 4:33}],
3:[{1:33 ,2:33, 3:33, 4:33}, {1:33 ,2:33, 3:33, 4:33}]}
What I want as output is the same structure but only the inner dictionary keys 1 and 2, I don't need 3 and 4 anymore:
d_new = {1: [{1: 33, 2: 33}, {1: 33, 2: 33}, {1: 33, 2: 33}],
2: [{1: 33, 2: 33}],
3: [{1: 33, 2: 33}, {1: 33, 2: 33}, {1: 33, 2: 33}]}
So far, I have two approaches which solve the problem but are very slow:
- Combination of list- and dict comprehension:
d_new = {n: [{1: d[1], 2: d[2]} for d in d[n]] for n in d.keys()}
- For-Loop
d_new = {}
keys = d.keys()
for key in keys:
storage = []
for x in d[key]:
storage.append({1: x[1], 2: x[2]})
d_new[key] = storage
They both solve the problem but are very slow when applied to large dictionaries so I am looking for a faster and more efficient way, maybe it is also possible to apply some kind of paralellization here. Very happy for any help!