diff --git a/dsp_permissions_scripts/oap/oap_serialize.py b/dsp_permissions_scripts/oap/oap_serialize.py index 990772fb..60fb8ac2 100644 --- a/dsp_permissions_scripts/oap/oap_serialize.py +++ b/dsp_permissions_scripts/oap/oap_serialize.py @@ -77,7 +77,14 @@ def _group_oaps_together(res_oaps: list[ResourceOap], val_oaps: list[ValueOap]) oaps: list[Oap] = [] deserialized_resource_iris = [] - for res_iri, _val_oaps in itertools.groupby(val_oaps, key=lambda x: x.resource_iri): + def sort_algo(x: ValueOap) -> str: + """ + According to https://docs.python.org/3/library/itertools.html#itertools.groupby, + the iterable must be sorted on the same key function, before passing it to itertools.groupby(). + """ + return x.resource_iri + + for res_iri, _val_oaps in itertools.groupby(sorted(val_oaps, key=sort_algo), key=sort_algo): res_oaps_filtered = [x for x in res_oaps if x.resource_iri == res_iri] res_oap = res_oaps_filtered[0] if res_oaps_filtered else None oaps.append(Oap(resource_oap=res_oap, value_oaps=sorted(_val_oaps, key=lambda x: x.value_iri)))