When using group_by to compare lists of dictionaries, if multiple dictionaries share the same key (e.g., the same 'id'), group_by alone might cause one dictionary to overwrite another in the internal grouping logic.
To prevent this and ensure all dictionaries are preserved and correctly compared, use the group_by_sort_key parameter. This parameter defines how the dictionaries within a group are sorted. When provided, group_by converts the lists into a dictionary where keys map to lists of dictionaries, and group_by_sort_key is used to sort those lists. This allows DeepDiff to track changes to specific items within a group even when they share a common identifier.
>>> t1 = [
... {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody', 'int_id': 2},
... {'id': 'BB', 'name': 'James', 'last_name': 'Blue', 'int_id': 20},
... {'id': 'BB', 'name': 'Jimmy', 'last_name': 'Red', 'int_id': 3},
... {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple', 'int_id': 4},
... ]
>>> t2 = [
... {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody', 'int_id': 2},
... {'id': 'BB', 'name': 'James', 'last_name': 'Brown', 'int_id': 20},
... {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple', 'int_id': 4},
... ]
>>> diff = DeepDiff(t1, t2, group_by='id', group_by_sort_key='name')
>>> pprint(diff)
{'iterable_item_removed': {"root['BB'][1]": {'int_id': 3,
'last_name': 'Red',
'name': 'Jimmy'}},
'values_changed': {"root['BB'][0]['last_name']": {'new_value': 'Brown',
'old_value': 'Blue'}}}