I need help to optimize my code.
I have a data:
data = [
{"ids": [1]},
{"ids": [3, 4]},
{"ids": [1, 2]},
{"ids": [2]},
]
and I need to group it without intersection by ids, so expected data should be:
expected = [
[{"ids": [1]}, {"ids": [2]}],
[{"ids": [3, 4]}, {"ids": [1, 2]}],
] # only 2 sublist here
My code to split(not optimized):
import itertools as it
def _split(
list_of_dicts,
):
splitted_list_of_dicts = []
sub_list = []
while list_of_dicts:
for dct in list_of_dicts:
ids_in_sub_list = set(
it.chain(*[sub_list_el["ids"] for sub_list_el in sub_list]),
)
if not set(dct["ids"]).intersection(ids_in_sub_list):
sub_list.append(dct)
list_of_dicts.remove(dct)
splitted_list_of_dicts.append(sub_list)
sub_list = []
return splitted_list_of_dicts
The result of my code is:
result = [
[{'ids': [1]}, {'ids': [2]}],
[{'ids': [3, 4]}],
[{'ids': [1, 2]}]
] # 3 sublist
I get one more list, which I try to optimize. If you have any ideas on how to help me, I'll be happy, thanks for your time.
More examples:
data = [
{"ids": [1]},
{"ids": [3, 4]},
{"ids": [1, 2]},
{"ids": [4]},
{"ids": [3]},
{"ids": [2]},
]
can be grouped as 2 elements list:
expected = [
[{'ids': [1]}, {'ids': [4]}, {'ids': [2]}, {'ids': [3]}],
[{'ids': [3, 4]}, {'ids': [1, 2]}],
]
but now I got all 4:
result = [
[{'ids': [1]}, {'ids': [4]}, {'ids': [2]}],
[{'ids': [3, 4]}],
[{'ids': [1, 2]}],
[{'ids': [3]}]
]