Added keylists core method.
This commit is contained in:
parent
df3bcb7a52
commit
d80b4d9537
|
@ -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
|
||||
|
|
|
@ -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, [])
|
|
@ -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
|
||||
|
|
|
@ -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)
|
Loading…
Reference in New Issue