Added keylists core method.

This commit is contained in:
Fabio Caccamo 2020-02-04 10:33:20 +01:00
parent df3bcb7a52
commit d80b4d9537
4 changed files with 82 additions and 11 deletions

View File

@ -8,6 +8,7 @@ from benedict.core.flatten import flatten
from benedict.core.invert import invert
from benedict.core.items_sorted import (
items_sorted_by_keys, items_sorted_by_values, )
from benedict.core.keylists import keylists
from benedict.core.keypaths import keypaths
from benedict.core.merge import merge
from benedict.core.move import move

17
benedict/core/keylists.py Normal file
View File

@ -0,0 +1,17 @@
# -*- coding: utf-8 -*-
from benedict.utils import type_util
def _get_keylist(item, parent_keys):
l = []
for key, value in item.items():
keys = parent_keys + [key]
l += [keys]
if type_util.is_dict(value):
l += _get_keylist(value, keys)
return l
def keylists(d):
return _get_keylist(d, [])

View File

@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
from benedict.core import keylists
from benedict.utils import type_util
@ -7,14 +8,7 @@ def keypaths(d, separator='.'):
if not separator or not type_util.is_string(separator):
raise ValueError('separator argument must be a (non-empty) string.')
def f(parent, parent_keys):
kp = []
for key, value in parent.items():
keys = parent_keys + [key]
kp += [separator.join('{}'.format(k) for k in keys)]
if type_util.is_dict(value):
kp += f(value, keys)
return kp
kp = f(d, [])
kp.sort()
return kp
kls = keylists(d)
kps = [separator.join(['{}'.format(key) for key in kl]) for kl in kls]
kps.sort()
return kps

View File

@ -0,0 +1,59 @@
# -*- coding: utf-8 -*-
from benedict.core import keylists as _keylists
import unittest
class keylists_test_case(unittest.TestCase):
def test_keylists(self):
i = {
'a': 1,
'b': {
'c': {
'x': 2,
'y': 3,
},
'd': {
'x': 4,
'y': 5,
},
},
}
o = _keylists(i)
r = [
['a'],
['b'],
['b', 'c'],
['b', 'c', 'x'],
['b', 'c', 'y'],
['b', 'd'],
['b', 'd', 'x'],
['b', 'd', 'y'],
]
self.assertEqual(o, r)
def test_keylists_with_non_string_keys(self):
i = {
True: {
True: 1,
},
False: {
False: 1,
},
None: {
None: 1,
},
}
o = _keylists(i)
r = [
[False],
[False, False],
[None],
[None, None],
[True],
[True, True],
]
for k in r:
self.assertTrue(k in o)