Debian Codegraph @

docs/basics.rst

raw
1 :doc:`/index`
2
3 Basics
4 ======
5
6
7 Importing
8 >>> from deepdiff import DeepDiff
9 >>> from pprint import pprint
10
11 Same object returns empty
12 >>> t1 = {1:1, 2:2, 3:3}
13 >>> t2 = t1
14 >>> print(DeepDiff(t1, t2))
15 {}
16
17 Type of an item has changed
18 >>> t1 = {1:1, 2:2, 3:3}
19 >>> t2 = {1:1, 2:"2", 3:3}
20 >>> pprint(DeepDiff(t1, t2), indent=2)
21 { 'type_changes': { 'root[2]': { 'new_type': <class 'str'>,
22 'new_value': '2',
23 'old_type': <class 'int'>,
24 'old_value': 2}}}
25
26 Value of an item has changed
27 >>> t1 = {1:1, 2:2, 3:3}
28 >>> t2 = {1:1, 2:4, 3:3}
29 >>> pprint(DeepDiff(t1, t2, verbose_level=0), indent=2)
30 {'values_changed': {'root[2]': {'new_value': 4, 'old_value': 2}}}
31
32 Item added and/or removed
33 >>> t1 = {1:1, 3:3, 4:4}
34 >>> t2 = {1:1, 3:3, 5:5, 6:6}
35 >>> ddiff = DeepDiff(t1, t2)
36 >>> pprint (ddiff)
37 {'dictionary_item_added': [root[5], root[6]],
38 'dictionary_item_removed': [root[4]]}
39
40 Set verbose level to 2 in order to see the added or removed items with their values
41 >>> t1 = {1:1, 3:3, 4:4}
42 >>> t2 = {1:1, 3:3, 5:5, 6:6}
43 >>> ddiff = DeepDiff(t1, t2, verbose_level=2)
44 >>> pprint(ddiff, indent=2)
45 { 'dictionary_item_added': {'root[5]': 5, 'root[6]': 6},
46 'dictionary_item_removed': {'root[4]': 4}}
47
48 Set verbose level to 2 includes new_path when the path has changed for a report between t1 and t2:
49 >>> t1 = [1, 3]
50 >>> t2 = [3, 2]
51 >>>
52 >>>
53 >>> diff = DeepDiff(t1, t2, ignore_order=True, verbose_level=2)
54 >>> pprint(diff)
55 {'values_changed': {'root[0]': {'new_path': 'root[1]',
56 'new_value': 2,
57 'old_value': 1}}}
58
59 String difference
60 >>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world"}}
61 >>> t2 = {1:1, 2:4, 3:3, 4:{"a":"hello", "b":"world!"}}
62 >>> ddiff = DeepDiff(t1, t2)
63 >>> pprint (ddiff, indent = 2)
64 { 'values_changed': { 'root[2]': {'new_value': 4, 'old_value': 2},
65 "root[4]['b']": { 'new_value': 'world!',
66 'old_value': 'world'}}}
67
68
69 String difference 2
70 >>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world!\nGoodbye!\n1\n2\nEnd"}}
71 >>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n1\n2\nEnd"}}
72 >>> ddiff = DeepDiff(t1, t2)
73 >>> pprint (ddiff, indent = 2)
74 { 'values_changed': { "root[4]['b']": { 'diff': '--- \n'
75 '+++ \n'
76 '@@ -1,5 +1,4 @@\n'
77 '-world!\n'
78 '-Goodbye!\n'
79 '+world\n'
80 ' 1\n'
81 ' 2\n'
82 ' End',
83 'new_value': 'world\n1\n2\nEnd',
84 'old_value': 'world!\n'
85 'Goodbye!\n'
86 '1\n'
87 '2\n'
88 'End'}}}
89
90 >>>
91 >>> print (ddiff['values_changed']["root[4]['b']"]["diff"])
92 ---
93 +++
94 @@ -1,5 +1,4 @@
95 -world!
96 -Goodbye!
97 +world
98 1
99 2
100 End
101
102 List difference
103 >>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3, 4]}}
104 >>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}}
105 >>> ddiff = DeepDiff(t1, t2)
106 >>> pprint (ddiff, indent = 2)
107 {'iterable_item_removed': {"root[4]['b'][2]": 3, "root[4]['b'][3]": 4}}
108
109 List that contains dictionary:
110 >>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:1, 2:2}]}}
111 >>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:3}]}}
112 >>> ddiff = DeepDiff(t1, t2)
113 >>> pprint (ddiff, indent = 2)
114 { 'dictionary_item_removed': [root[4]['b'][2][2]],
115 'values_changed': {"root[4]['b'][2][1]": {'new_value': 3, 'old_value': 1}}}
116
117 Sets:
118 >>> t1 = {1, 2, 8}
119 >>> t2 = {1, 2, 3, 5}
120 >>> ddiff = DeepDiff(t1, t2)
121 >>> pprint(ddiff)
122 {'set_item_added': [root[3], root[5]], 'set_item_removed': [root[8]]}
123
124 Named Tuples:
125 >>> from collections import namedtuple
126 >>> Point = namedtuple('Point', ['x', 'y'])
127 >>> t1 = Point(x=11, y=22)
128 >>> t2 = Point(x=11, y=23)
129 >>> pprint (DeepDiff(t1, t2))
130 {'values_changed': {'root.y': {'new_value': 23, 'old_value': 22}}}
131
132 Custom objects:
133 >>> class ClassA(object):
134 ... a = 1
135 ... def __init__(self, b):
136 ... self.b = b
137 ...
138 >>> t1 = ClassA(1)
139 >>> t2 = ClassA(2)
140 >>>
141 >>> pprint(DeepDiff(t1, t2))
142 {'values_changed': {'root.b': {'new_value': 2, 'old_value': 1}}}
143
144 Object attribute added:
145 >>> t2.c = "new attribute"
146 >>> pprint(DeepDiff(t1, t2))
147 {'attribute_added': [root.c],
148 'values_changed': {'root.b': {'new_value': 2, 'old_value': 1}}}
149
150
151 Datetime
152 DeepDiff converts all datetimes into UTC. If a datetime is timezone naive, we assume it is in UTC too.
153 That is different than what Python does. Python assumes your timezone naive datetime is in your local timezone.
154 >>> from deepdiff import DeepDiff
155 >>> from datetime import datetime, timezone
156 >>> d1 = datetime(2020, 8, 31, 13, 14, 1)
157 >>> d2 = datetime(2020, 8, 31, 13, 14, 1, tzinfo=timezone.utc)
158 >>> d1 == d2
159 False
160 >>> DeepDiff(d1, d2)
161 {}
162
163
164 .. note::
165 All the examples above use the default :ref:`text_view_label`.
166 If you want traversing functionality in the results, use the :ref:`tree_view_label`.
167 You just need to set view='tree' to get it in tree form.
168
169
170 .. _group_by_label:
171
172 Group By
173 --------
174
175 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. It is also possible to have a callable group_by, which can be used to access keys in more nested data structures.
176
177 For example:
178 >>> [
179 ... {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
180 ... {'id': 'BB', 'name': 'James', 'last_name': 'Blue'},
181 ... {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'},
182 ... ]
183
184 Becomes:
185 >>> t1 = {
186 ... 'AA': {'name': 'Joe', 'last_name': 'Nobody'},
187 ... 'BB': {'name': 'James', 'last_name': 'Blue'},
188 ... 'CC': {'name': 'Mike', 'last_name': 'Apple'},
189 ... }
190
191
192 With that in mind, let's take a look at the following:
193 >>> from deepdiff import DeepDiff
194 >>> t1 = [
195 ... {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
196 ... {'id': 'BB', 'name': 'James', 'last_name': 'Blue'},
197 ... {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'},
198 ... ]
199 >>>
200 >>> t2 = [
201 ... {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
202 ... {'id': 'BB', 'name': 'James', 'last_name': 'Brown'},
203 ... {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'},
204 ... ]
205 >>>
206 >>> DeepDiff(t1, t2)
207 {'values_changed': {"root[1]['last_name']": {'new_value': 'Brown', 'old_value': 'Blue'}}}
208
209
210 Now we use group_by='id':
211 >>> DeepDiff(t1, t2, group_by='id')
212 {'values_changed': {"root['BB']['last_name']": {'new_value': 'Brown', 'old_value': 'Blue'}}}
213
214 .. note::
215 group_by actually changes the structure of the t1 and t2. You can see this by using the tree view:
216
217 >>> diff = DeepDiff(t1, t2, group_by='id', view='tree')
218 >>> diff
219 {'values_changed': [<root['BB']['last_name'] t1:'Blue', t2:'Brown'>]}
220 >>> diff['values_changed'][0]
221 <root['BB']['last_name'] t1:'Blue', t2:'Brown'>
222 >>> diff['values_changed'][0].up
223 <root['BB'] t1:{'name': 'Ja...}, t2:{'name': 'Ja...}>
224 >>> diff['values_changed'][0].up.up
225 <root t1:{'AA': {'nam...}, t2:{'AA': {'nam...}>
226 >>> diff['values_changed'][0].up.up.t1
227 {'AA': {'name': 'Joe', 'last_name': 'Nobody'}, 'BB': {'name': 'James', 'last_name': 'Blue'}, 'CC': {'name': 'Mike', 'last_name': 'Apple'}}
228
229 2D Example:
230 >>> from pprint import pprint
231 >>> from deepdiff import DeepDiff
232 >>>
233 >>> t1 = [
234 ... {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
235 ... {'id': 'BB', 'name': 'James', 'last_name': 'Blue'},
236 ... {'id': 'BB', 'name': 'Jimmy', 'last_name': 'Red'},
237 ... {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'},
238 ... ]
239 >>>
240 >>> t2 = [
241 ... {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
242 ... {'id': 'BB', 'name': 'James', 'last_name': 'Brown'},
243 ... {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'},
244 ... ]
245 >>>
246 >>> diff = DeepDiff(t1, t2, group_by=['id', 'name'])
247 >>> pprint(diff)
248 {'dictionary_item_removed': [root['BB']['Jimmy']],
249 'values_changed': {"root['BB']['James']['last_name']": {'new_value': 'Brown',
250 'old_value': 'Blue'}}}
251
252 Callable group_by Example:
253 >>> from deepdiff import DeepDiff
254 >>>
255 >>> t1 = [
256 ... {'id': 'AA', 'demographics': {'names': {'first': 'Joe', 'middle': 'John', 'last': 'Nobody'}}},
257 ... {'id': 'BB', 'demographics': {'names': {'first': 'James', 'middle': 'Joyce', 'last': 'Blue'}}},
258 ... {'id': 'CC', 'demographics': {'names': {'first': 'Mike', 'middle': 'Mark', 'last': 'Apple'}}},
259 ... ]
260 >>>
261 >>> t2 = [
262 ... {'id': 'AA', 'demographics': {'names': {'first': 'Joe', 'middle': 'John', 'last': 'Nobody'}}},
263 ... {'id': 'BB', 'demographics': {'names': {'first': 'James', 'middle': 'Joyce', 'last': 'Brown'}}},
264 ... {'id': 'CC', 'demographics': {'names': {'first': 'Mike', 'middle': 'Charles', 'last': 'Apple'}}},
265 ... ]
266 >>>
267 >>> diff = DeepDiff(t1, t2, group_by=lambda x: x['demographics']['names']['first'])
268 >>> pprint(diff)
269 {'values_changed': {"root['James']['demographics']['names']['last']": {'new_value': 'Brown',
270 'old_value': 'Blue'},
271 "root['Mike']['demographics']['names']['middle']": {'new_value': 'Charles',
272 'old_value': 'Mark'}}}
273
274 .. _group_by_sort_key_label:
275
276 Group By - Sort Key
277 -------------------
278
279 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.
280
281 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'.
282
283 Example:
284 >>> [{'id': 'AA', 'int_id': 2, 'last_name': 'Nobody', 'name': 'Joe'},
285 ... {'id': 'BB', 'int_id': 20, 'last_name': 'Blue', 'name': 'James'},
286 ... {'id': 'BB', 'int_id': 3, 'last_name': 'Red', 'name': 'Jimmy'},
287 ... {'id': 'CC', 'int_id': 4, 'last_name': 'Apple', 'name': 'Mike'}]
288
289
290 Becomes:
291 >>> {'AA': [{'int_id': 2, 'last_name': 'Nobody', 'name': 'Joe'}],
292 ... 'BB': [{'int_id': 20, 'last_name': 'Blue', 'name': 'James'},
293 ... {'int_id': 3, 'last_name': 'Red', 'name': 'Jimmy'}],
294 ... 'CC': [{'int_id': 4, 'last_name': 'Apple', 'name': 'Mike'}]}
295
296
297 Example of using group_by_sort_key
298 >>> t1 = [
299 ... {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody', 'int_id': 2},
300 ... {'id': 'BB', 'name': 'James', 'last_name': 'Blue', 'int_id': 20},
301 ... {'id': 'BB', 'name': 'Jimmy', 'last_name': 'Red', 'int_id': 3},
302 ... {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple', 'int_id': 4},
303 ... ]
304 >>>
305 >>> t2 = [
306 ... {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody', 'int_id': 2},
307 ... {'id': 'BB', 'name': 'James', 'last_name': 'Brown', 'int_id': 20},
308 ... {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple', 'int_id': 4},
309 ... ]
310 >>>
311 >>> diff = DeepDiff(t1, t2, group_by='id', group_by_sort_key='name')
312 >>>
313 >>> pprint(diff)
314 {'iterable_item_removed': {"root['BB'][1]": {'int_id': 3,
315 'last_name': 'Red',
316 'name': 'Jimmy'}},
317 'values_changed': {"root['BB'][0]['last_name']": {'new_value': 'Brown',
318 'old_value': 'Blue'}}}
319
320
321 .. _default_timezone_label:
322
323 Default Time Zone
324 -----------------
325
326 default_timezone defines the default timezone. If a datetime is timezone naive, which means it doesn't have a timezone, we assume the datetime is in this timezone. Also any datetime that has a timezone will be converted to this timezone so the datetimes can be compared properly all in the same timezone. Note that Python's default behavior assumes the default timezone is your local timezone. DeepDiff's default is UTC, not your local time zone.
327
328
329 Note that if we change the default_timezone, the output timezone changes accordingly
330 >>> from deepdiff import DeepDiff
331 >>> import pytz
332 >>> from datetime import date, datetime, time, timezone
333 >>> dt_utc = datetime(2025, 2, 3, 12, 0, 0, tzinfo=pytz.utc) # UTC timezone
334 >>> dt_utc2 = datetime(2025, 2, 3, 11, 0, 0, tzinfo=pytz.utc) # UTC timezone
335 >>> dt_ny = dt_utc.astimezone(pytz.timezone('America/New_York'))
336 >>> dt_ny2 = dt_utc2.astimezone(pytz.timezone('America/New_York'))
337 >>> diff = DeepDiff(dt_ny, dt_ny2)
338 >>> diff
339 {'values_changed': {'root': {'new_value': datetime.datetime(2025, 2, 3, 11, 0, tzinfo=datetime.timezone.utc), 'old_value': datetime.datetime(2025, 2, 3, 12, 0, tzinfo=datetime.timezone.utc)}}}
340 >>> diff2 = DeepDiff(dt_ny, dt_ny2, default_timezone=pytz.timezone('America/New_York'))
341 >>> diff2
342 {'values_changed': {'root': {'new_value': datetime.datetime(2025, 2, 3, 6, 0, tzinfo=<DstTzInfo 'America/New_York' EST-1 day, 19:00:00 STD>), 'old_value': datetime.datetime(2025, 2, 3, 7, 0, tzinfo=<DstTzInfo 'America/New_York' EST-1 day, 19:00:00 STD>)}}}
343
344
345 Back to :doc:`/index`