Skip to content

Commit e586fd6

Browse files
authored
Merge pull request #427 from seperman/dev
6.6.1
2 parents 17f34a7 + 3154215 commit e586fd6

15 files changed

+286
-40
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# DeepDiff Change log
22

3+
- v6-6-1
4+
- Fix for [DeepDiff raises decimal exception when using significant digits](https://github.com/seperman/deepdiff/issues/426)
5+
- Introducing group_by_sort_key
6+
- Adding group_by 2D. For example `group_by=['last_name', 'zip_code']`
37
- v6-6-0
48
- Numpy 2.0 support
59
- Adding [Delta.to_flat_dicts](https://zepworks.com/deepdiff/current/serialization.html#delta-serialize-to-flat-dictionaries)

README.md

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# DeepDiff v 6.6.0
1+
# DeepDiff v 6.6.1
22

33
![Downloads](https://img.shields.io/pypi/dm/deepdiff.svg?style=flat)
44
![Python Versions](https://img.shields.io/pypi/pyversions/deepdiff.svg?style=flat)
@@ -17,15 +17,21 @@
1717

1818
Tested on Python 3.7+ and PyPy3.
1919

20-
- **[Documentation](https://zepworks.com/deepdiff/6.6.0/)**
20+
- **[Documentation](https://zepworks.com/deepdiff/6.6.1/)**
2121

2222
## What is new?
2323

2424
Please check the [ChangeLog](CHANGELOG.md) file for the detailed information.
2525

26+
DeepDiff 6-6-1
27+
- Fix for [DeepDiff raises decimal exception when using significant digits](https://github.com/seperman/deepdiff/issues/426)
28+
- Introducing group_by_sort_key
29+
- Adding group_by 2D. For example `group_by=['last_name', 'zip_code']`
30+
31+
2632
DeepDiff 6-6-0
2733

28-
- [Serialize To Flat Dicts]()
34+
- [Serialize To Flat Dicts](https://zepworks.com/deepdiff/current/serialization.html#delta-to-flat-dicts-label)
2935
- [NumPy 2.0 compatibility](https://github.com/seperman/deepdiff/pull/422) by [William Jamieson](https://github.com/WilliamJamieson)
3036

3137
DeepDiff 6-5-0
@@ -101,11 +107,11 @@ Thank you!
101107

102108
How to cite this library (APA style):
103109

104-
Dehpour, S. (2023). DeepDiff (Version 6.6.0) [Software]. Available from https://github.com/seperman/deepdiff.
110+
Dehpour, S. (2023). DeepDiff (Version 6.6.1) [Software]. Available from https://github.com/seperman/deepdiff.
105111

106112
How to cite this library (Chicago style):
107113

108-
Dehpour, Sep. 2023. DeepDiff (version 6.6.0).
114+
Dehpour, Sep. 2023. DeepDiff (version 6.6.1).
109115

110116
# Authors
111117

deepdiff/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""This module offers the DeepDiff, DeepSearch, grep, Delta and DeepHash classes."""
22
# flake8: noqa
3-
__version__ = '6.6.0'
3+
__version__ = '6.6.1'
44
import logging
55

66
if __name__ == '__main__':

deepdiff/diff.py

Lines changed: 55 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ def __init__(self,
130130
exclude_types=None,
131131
get_deep_distance=False,
132132
group_by=None,
133+
group_by_sort_key=None,
133134
hasher=None,
134135
hashes=None,
135136
ignore_encoding_errors=False,
@@ -170,7 +171,7 @@ def __init__(self,
170171
"ignore_private_variables, ignore_nan_inequality, number_to_string_func, verbose_level, "
171172
"view, hasher, hashes, max_passes, max_diffs, zip_ordered_iterables, "
172173
"cutoff_distance_for_pairs, cutoff_intersection_for_pairs, log_frequency_in_sec, cache_size, "
173-
"cache_tuning_sample_size, get_deep_distance, group_by, cache_purge_level, "
174+
"cache_tuning_sample_size, get_deep_distance, group_by, group_by_sort_key, cache_purge_level, "
174175
"math_epsilon, iterable_compare_func, _original_type, "
175176
"ignore_order_func, custom_operators, encodings, ignore_encoding_errors, "
176177
"_parameters and _shared_parameters.") % ', '.join(kwargs.keys()))
@@ -216,6 +217,14 @@ def __init__(self,
216217
self.hasher = hasher
217218
self.cache_tuning_sample_size = cache_tuning_sample_size
218219
self.group_by = group_by
220+
if callable(group_by_sort_key):
221+
self.group_by_sort_key = group_by_sort_key
222+
elif group_by_sort_key:
223+
def _group_by_sort_key(x):
224+
return x[group_by_sort_key]
225+
self.group_by_sort_key = _group_by_sort_key
226+
else:
227+
self.group_by_sort_key = None
219228
self.encodings = encodings
220229
self.ignore_encoding_errors = ignore_encoding_errors
221230

@@ -1592,26 +1601,64 @@ def _get_view_results(self, view):
15921601
raise ValueError(INVALID_VIEW_MSG.format(view))
15931602
return result
15941603

1604+
@staticmethod
1605+
def _get_key_for_group_by(row, group_by, item_name):
1606+
try:
1607+
return row.pop(group_by)
1608+
except KeyError:
1609+
logger.error("Unable to group {} by {}. The key is missing in {}".format(item_name, group_by, row))
1610+
raise
1611+
15951612
def _group_iterable_to_dict(self, item, group_by, item_name):
15961613
"""
15971614
Convert a list of dictionaries into a dictionary of dictionaries
15981615
where the key is the value of the group_by key in each dictionary.
15991616
"""
1617+
group_by_level2 = None
1618+
if isinstance(group_by, (list, tuple)):
1619+
group_by_level1 = group_by[0]
1620+
if len(group_by) > 1:
1621+
group_by_level2 = group_by[1]
1622+
else:
1623+
group_by_level1 = group_by
16001624
if isinstance(item, Iterable) and not isinstance(item, Mapping):
16011625
result = {}
16021626
item_copy = deepcopy(item)
16031627
for row in item_copy:
16041628
if isinstance(row, Mapping):
1605-
try:
1606-
key = row.pop(group_by)
1607-
except KeyError:
1608-
logger.error("Unable to group {} by {}. The key is missing in {}".format(item_name, group_by, row))
1609-
raise
1610-
result[key] = row
1629+
key1 = self._get_key_for_group_by(row, group_by_level1, item_name)
1630+
if group_by_level2:
1631+
key2 = self._get_key_for_group_by(row, group_by_level2, item_name)
1632+
if key1 not in result:
1633+
result[key1] = {}
1634+
if self.group_by_sort_key:
1635+
if key2 not in result[key1]:
1636+
result[key1][key2] = []
1637+
result_key1_key2 = result[key1][key2]
1638+
if row not in result_key1_key2:
1639+
result_key1_key2.append(row)
1640+
else:
1641+
result[key1][key2] = row
1642+
else:
1643+
if self.group_by_sort_key:
1644+
if key1 not in result:
1645+
result[key1] = []
1646+
if row not in result[key1]:
1647+
result[key1].append(row)
1648+
else:
1649+
result[key1] = row
16111650
else:
1612-
msg = "Unable to group {} by {} since the item {} is not a dictionary.".format(item_name, group_by, row)
1651+
msg = "Unable to group {} by {} since the item {} is not a dictionary.".format(item_name, group_by_level1, row)
16131652
logger.error(msg)
16141653
raise ValueError(msg)
1654+
if self.group_by_sort_key:
1655+
if group_by_level2:
1656+
for key1, row1 in result.items():
1657+
for key2, row in row1.items():
1658+
row.sort(key=self.group_by_sort_key)
1659+
else:
1660+
for key, row in result.items():
1661+
row.sort(key=self.group_by_sort_key)
16151662
return result
16161663
msg = "Unable to group {} by {}".format(item_name, group_by)
16171664
logger.error(msg)

deepdiff/helper.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import string
99
import time
1010
from ast import literal_eval
11-
from decimal import Decimal, localcontext
11+
from decimal import Decimal, localcontext, InvalidOperation as InvalidDecimalOperation
1212
from collections import namedtuple
1313
from itertools import repeat
1414
from ordered_set import OrderedSet
@@ -394,7 +394,13 @@ def number_to_string(number, significant_digits, number_format_notation="f"):
394394
# Precision = number of integer digits + significant_digits
395395
# Using number//1 to get the integer part of the number
396396
ctx.prec = len(str(abs(number // 1))) + significant_digits
397-
number = number.quantize(Decimal('0.' + '0' * significant_digits))
397+
try:
398+
number = number.quantize(Decimal('0.' + '0' * significant_digits))
399+
except InvalidDecimalOperation:
400+
# Sometimes rounding up causes a higher precision to be needed for the quantize operation
401+
# For example '999.99999999' will become '1000.000000' after quantize
402+
ctx.prec += 1
403+
number = number.quantize(Decimal('0.' + '0' * significant_digits))
398404
elif isinstance(number, only_complex_number):
399405
# Case for complex numbers.
400406
number = number.__class__(

deepdiff/serialization.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -537,6 +537,7 @@ def _serialize_decimal(value):
537537
JSON_CONVERTOR = {
538538
decimal.Decimal: _serialize_decimal,
539539
ordered_set.OrderedSet: list,
540+
set: list,
540541
type: lambda x: x.__name__,
541542
bytes: lambda x: x.decode('utf-8'),
542543
datetime.datetime: lambda x: x.isoformat(),

docs/basics.rst

Lines changed: 87 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,9 +148,24 @@ Object attribute added:
148148
Group By
149149
--------
150150

151-
group_by can be used when dealing with list of dictionaries to convert them to group them by value defined in group_by. The common use case is when reading data from a flat CSV and primary key is one of the columns in the CSV. We want to use the primary key to group the rows instead of CSV row number.
151+
group_by can be used when dealing with the list of dictionaries. It converts them from lists to a single dictionary with the key defined by group_by. The common use case is when reading data from a flat CSV, and the primary key is one of the columns in the CSV. We want to use the primary key instead of the CSV row number to group the rows. The group_by can do 2D group_by by passing a list of 2 keys.
152152

153-
Example:
153+
For example:
154+
>>> [
155+
... {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
156+
... {'id': 'BB', 'name': 'James', 'last_name': 'Blue'},
157+
... {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'},
158+
... ]
159+
160+
Becomes:
161+
>>> t1 = {
162+
... 'AA': {'name': 'Joe', 'last_name': 'Nobody'},
163+
... 'BB': {'name': 'James', 'last_name': 'Blue'},
164+
... 'CC': {'name': 'Mike', 'last_name': 'Apple'},
165+
... }
166+
167+
168+
With that in mind, let's take a look at the following:
154169
>>> from deepdiff import DeepDiff
155170
>>> t1 = [
156171
... {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
@@ -187,5 +202,75 @@ Now we use group_by='id':
187202
>>> diff['values_changed'][0].up.up.t1
188203
{'AA': {'name': 'Joe', 'last_name': 'Nobody'}, 'BB': {'name': 'James', 'last_name': 'Blue'}, 'CC': {'name': 'Mike', 'last_name': 'Apple'}}
189204

205+
2D Example:
206+
>>> from pprint import pprint
207+
>>> from deepdiff import DeepDiff
208+
>>>
209+
>>> t1 = [
210+
... {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
211+
... {'id': 'BB', 'name': 'James', 'last_name': 'Blue'},
212+
... {'id': 'BB', 'name': 'Jimmy', 'last_name': 'Red'},
213+
... {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'},
214+
... ]
215+
>>>
216+
>>> t2 = [
217+
... {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
218+
... {'id': 'BB', 'name': 'James', 'last_name': 'Brown'},
219+
... {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'},
220+
... ]
221+
>>>
222+
>>> diff = DeepDiff(t1, t2, group_by=['id', 'name'])
223+
>>> pprint(diff)
224+
{'dictionary_item_removed': [root['BB']['Jimmy']],
225+
'values_changed': {"root['BB']['James']['last_name']": {'new_value': 'Brown',
226+
'old_value': 'Blue'}}}
227+
228+
.. _group_by_sort_key_label:
229+
230+
Group By - Sort Key
231+
-------------------
232+
233+
group_by_sort_key is used to define how dictionaries are sorted if multiple ones fall under one group. When this parameter is used, group_by converts the lists of dictionaries into a dictionary of keys to lists of dictionaries. Then, group_by_sort_key is used to sort between the list.
234+
235+
For example, there are duplicate id values. If we only use group_by='id', one of the dictionaries with id of 'BB' will overwrite the other. However, if we also set group_by_sort_key='name', we keep both dictionaries with the id of 'BB'.
236+
237+
Example:
238+
239+
[{'id': 'AA', 'int_id': 2, 'last_name': 'Nobody', 'name': 'Joe'},
240+
{'id': 'BB', 'int_id': 20, 'last_name': 'Blue', 'name': 'James'},
241+
{'id': 'BB', 'int_id': 3, 'last_name': 'Red', 'name': 'Jimmy'},
242+
{'id': 'CC', 'int_id': 4, 'last_name': 'Apple', 'name': 'Mike'}]
243+
244+
245+
Becomes:
246+
{'AA': [{'int_id': 2, 'last_name': 'Nobody', 'name': 'Joe'}],
247+
'BB': [{'int_id': 20, 'last_name': 'Blue', 'name': 'James'},
248+
{'int_id': 3, 'last_name': 'Red', 'name': 'Jimmy'}],
249+
'CC': [{'int_id': 4, 'last_name': 'Apple', 'name': 'Mike'}]}
250+
251+
252+
Example of using group_by_sort_key
253+
>>> t1 = [
254+
... {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody', 'int_id': 2},
255+
... {'id': 'BB', 'name': 'James', 'last_name': 'Blue', 'int_id': 20},
256+
... {'id': 'BB', 'name': 'Jimmy', 'last_name': 'Red', 'int_id': 3},
257+
... {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple', 'int_id': 4},
258+
... ]
259+
>>>
260+
>>> t2 = [
261+
... {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody', 'int_id': 2},
262+
... {'id': 'BB', 'name': 'James', 'last_name': 'Brown', 'int_id': 20},
263+
... {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple', 'int_id': 4},
264+
... ]
265+
>>>
266+
>>> diff = DeepDiff(t1, t2, group_by='id', group_by_sort_key='name')
267+
>>>
268+
>>> pprint(diff)
269+
{'iterable_item_removed': {"root['BB'][1]": {'int_id': 3,
270+
'last_name': 'Red',
271+
'name': 'Jimmy'}},
272+
'values_changed': {"root['BB'][0]['last_name']": {'new_value': 'Brown',
273+
'old_value': 'Blue'}}}
274+
190275

191276
Back to :doc:`/index`

docs/changelog.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,14 @@ Changelog
55

66
DeepDiff Changelog
77

8+
- v6-6-1
9+
10+
- Fix for `DeepDiff raises decimal exception when using significant
11+
digits <https://github.com/seperman/deepdiff/issues/426>`__
12+
- Introducing group_by_sort_key
13+
- Adding group_by 2D. For example
14+
``group_by=['last_name', 'zip_code']``
15+
816
- v6-6-0
917

1018
- Numpy 2.0 support

docs/conf.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,9 @@
6161
# built documents.
6262
#
6363
# The short X.Y version.
64-
version = '6.6.0'
64+
version = '6.6.1'
6565
# The full version, including alpha/beta/rc tags.
66-
release = '6.6.0'
66+
release = '6.6.1'
6767

6868
load_dotenv(override=True)
6969
DOC_VERSION = os.environ.get('DOC_VERSION', version)

docs/diff_doc.rst

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,11 @@ include_obj_callback_strict: function, default = None
7979
get_deep_distance: Boolean, default = False
8080
:ref:`get_deep_distance_label` will get you the deep distance between objects. The distance is a number between 0 and 1 where zero means there is no diff between the 2 objects and 1 means they are very different. Note that this number should only be used to compare the similarity of 2 objects and nothing more. The algorithm for calculating this number may or may not change in the future releases of DeepDiff.
8181

82-
group_by: String, default=None
83-
:ref:`group_by_label` can be used when dealing with list of dictionaries to convert them to group them by value defined in group_by. The common use case is when reading data from a flat CSV and primary key is one of the columns in the CSV. We want to use the primary key to group the rows instead of CSV row number.
82+
group_by: String or a list of size 2, default=None
83+
:ref:`group_by_label` can be used when dealing with the list of dictionaries. It converts them from lists to a single dictionary with the key defined by group_by. The common use case is when reading data from a flat CSV, and the primary key is one of the columns in the CSV. We want to use the primary key instead of the CSV row number to group the rows. The group_by can do 2D group_by by passing a list of 2 keys.
84+
85+
group_by_sort_key: String or a function
86+
:ref:`group_by_sort_key_label` is used to define how dictionaries are sorted if multiple ones fall under one group. When this parameter is used, group_by converts the lists of dictionaries into a dictionary of keys to lists of dictionaries. Then, :ref:`group_by_sort_key_label` is used to sort between the list.
8487

8588
hasher: default = DeepHash.sha256hex
8689
Hash function to be used. If you don't want SHA256, you can use your own hash function

docs/index.rst

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
contain the root `toctree` directive.
55
66
7-
DeepDiff 6.6.0 documentation!
7+
DeepDiff 6.6.1 documentation!
88
=============================
99

1010
*******
@@ -31,6 +31,15 @@ The DeepDiff library includes the following modules:
3131
What Is New
3232
***********
3333

34+
DeepDiff 6-6-1
35+
--------------
36+
37+
- Fix for `DeepDiff raises decimal exception when using significant
38+
digits <https://github.com/seperman/deepdiff/issues/426>`__
39+
- Introducing group_by_sort_key
40+
- Adding group_by 2D. For example
41+
``group_by=['last_name', 'zip_code']``
42+
3443
DeepDiff 6-6-0
3544
--------------
3645

setup.cfg

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[bumpversion]
2-
current_version = 6.6.0
2+
current_version = 6.6.1
33
commit = True
44
tag = True
55
tag_name = {new_version}

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
if os.environ.get('USER', '') == 'vagrant':
1111
del os.link
1212

13-
version = '6.6.0'
13+
version = '6.6.1'
1414

1515

1616
def get_reqs(filename):

0 commit comments

Comments
 (0)