Skip to content

Commit cd5117e

Browse files
authored
Add 'sort' parameter to keypaths method. (#467)
1 parent 58f62a5 commit cd5117e

File tree

4 files changed

+36
-5
lines changed

4 files changed

+36
-5
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,8 @@ items = d.items_sorted_by_values(reverse=False)
458458
```python
459459
# Return a list of all keypaths in the dict.
460460
# If indexes is True, the output will include list values indexes.
461-
k = d.keypaths(indexes=False)
461+
# If sort is True, the resulting list will be sorted
462+
k = d.keypaths(indexes=False, sort=True)
462463
```
463464

464465
#### `match`

benedict/core/keypaths.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22
from benedict.utils import type_util
33

44

5-
def keypaths(d, separator=".", indexes=False):
5+
def keypaths(d, separator=".", indexes=False, sort=True):
66
separator = separator or "."
77
if not type_util.is_string(separator):
88
raise ValueError("separator argument must be a (non-empty) string.")
99
kls = keylists(d, indexes=indexes)
1010
kps = [separator.join([f"{key}" for key in kl]) for kl in kls]
11-
kps.sort()
11+
if sort:
12+
kps.sort()
1213
return kps

benedict/dicts/__init__.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,12 +196,14 @@ def items_sorted_by_values(self, reverse=False):
196196
"""
197197
return _items_sorted_by_values(self, reverse=reverse)
198198

199-
def keypaths(self, indexes=False):
199+
def keypaths(self, indexes=False, sort=True):
200200
"""
201201
Return a list of all keypaths in the dict.
202202
If indexes is True, the output will include list values indexes.
203203
"""
204-
return _keypaths(self, separator=self._keypath_separator, indexes=indexes)
204+
return _keypaths(
205+
self, separator=self._keypath_separator, indexes=indexes, sort=sort
206+
)
205207

206208
def match(self, pattern, indexes=True):
207209
"""

tests/core/test_keypaths.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,33 @@ def test_keypaths(self):
3535
]
3636
self.assertEqual(o, r)
3737

38+
def test_keypaths_unsorted(self):
39+
i = {
40+
"b": {
41+
"c": {
42+
"y": 3,
43+
"x": 2,
44+
},
45+
"d": {
46+
"x": 4,
47+
"y": 5,
48+
},
49+
},
50+
"a": 1,
51+
}
52+
o = _keypaths(i, sort=False)
53+
r = [
54+
"b",
55+
"b.c",
56+
"b.c.y",
57+
"b.c.x",
58+
"b.d",
59+
"b.d.x",
60+
"b.d.y",
61+
"a",
62+
]
63+
self.assertEqual(o, r)
64+
3865
def test_keypaths_with_custom_separator(self):
3966
i = {
4067
"a": 1,

0 commit comments

Comments
 (0)