Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,8 @@ items = d.items_sorted_by_values(reverse=False)
```python
# Return a list of all keypaths in the dict.
# If indexes is True, the output will include list values indexes.
k = d.keypaths(indexes=False)
# If sort is True, the resulting list will be sorted
k = d.keypaths(indexes=False, sort=True)
```

#### `match`
Expand Down
5 changes: 3 additions & 2 deletions benedict/core/keypaths.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@
from benedict.utils import type_util


def keypaths(d, separator=".", indexes=False):
def keypaths(d, separator=".", indexes=False, sort=True):
separator = separator or "."
if not type_util.is_string(separator):
raise ValueError("separator argument must be a (non-empty) string.")
kls = keylists(d, indexes=indexes)
kps = [separator.join([f"{key}" for key in kl]) for kl in kls]
kps.sort()
if sort:
kps.sort()
return kps
6 changes: 4 additions & 2 deletions benedict/dicts/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,14 @@ def items_sorted_by_values(self, reverse=False):
"""
return _items_sorted_by_values(self, reverse=reverse)

def keypaths(self, indexes=False):
def keypaths(self, indexes=False, sort=True):
"""
Return a list of all keypaths in the dict.
If indexes is True, the output will include list values indexes.
"""
return _keypaths(self, separator=self._keypath_separator, indexes=indexes)
return _keypaths(
self, separator=self._keypath_separator, indexes=indexes, sort=sort
)

def match(self, pattern, indexes=True):
"""
Expand Down
27 changes: 27 additions & 0 deletions tests/core/test_keypaths.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,33 @@ def test_keypaths(self):
]
self.assertEqual(o, r)

def test_keypaths_unsorted(self):
i = {
"b": {
"c": {
"y": 3,
"x": 2,
},
"d": {
"x": 4,
"y": 5,
},
},
"a": 1,
}
o = _keypaths(i, sort=False)
r = [
"b",
"b.c",
"b.c.y",
"b.c.x",
"b.d",
"b.d.x",
"b.d.y",
"a",
]
self.assertEqual(o, r)

def test_keypaths_with_custom_separator(self):
i = {
"a": 1,
Expand Down
Loading