Skip to content

Commit f1fc918

Browse files
committed
enable callable group_by
1 parent 0978fb8 commit f1fc918

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

deepdiff/diff.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ def __init__(self,
157157
exclude_regex_paths: Union[str, List[str], Pattern[str], List[Pattern[str]], None]=None,
158158
exclude_types: Optional[List[type]]=None,
159159
get_deep_distance: bool=False,
160-
group_by: Union[str, Tuple[str, str], None]=None,
160+
group_by: Union[str, Tuple[str, str], Callable, None]=None,
161161
group_by_sort_key: Union[str, Callable, None]=None,
162162
hasher: Optional[Callable]=None,
163163
hashes: Optional[Dict[Any, Any]]=None,
@@ -1834,7 +1834,32 @@ def _get_view_results(self, view):
18341834

18351835
@staticmethod
18361836
def _get_key_for_group_by(row, group_by, item_name):
1837+
"""
1838+
Get the key value to group a row by, using the specified group_by parameter.
1839+
1840+
Example
1841+
>>> row = {'first': 'John', 'middle': 'Joe', 'last': 'Smith'}
1842+
>>> group_by_key = DeepDiff._get_key_for_group_by(row, 'first', 't1')
1843+
'John'
1844+
>>> nested_row = {'id': 123, 'demographics': {'names': {'first': 'John', 'middle': 'Joe', 'last': 'Smith'}}}
1845+
>>> group_by_key = DeepDiff._get_key_for_group_by(nested_row,
1846+
lambda x: x['demographics']['names']['first'], 't1')
1847+
'John'
1848+
1849+
Args:
1850+
row (dict): The dictionary (row) to extract the group by key from.
1851+
group_by (str or callable): The key name or function to call to get to the key value to group by.
1852+
item_name (str): The name of the item, used for error messages.
1853+
1854+
Returns:
1855+
str: The key value to group by.
1856+
1857+
Raises:
1858+
KeyError: If the specified key is not found in the row.
1859+
"""
18371860
try:
1861+
if callable(group_by):
1862+
return group_by(row)
18381863
return row.pop(group_by)
18391864
except KeyError:
18401865
logger.error("Unable to group {} by {}. The key is missing in {}".format(item_name, group_by, row))

0 commit comments

Comments
 (0)