Created
January 30, 2020 10:50
-
-
Save XCanG/17a7f3999674a9aa4457074bc1beae1f to your computer and use it in GitHub Desktop.
Convert dict pairs to dict tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source = [ | |
(None, 'a'), | |
(None, 'b'), | |
(None, 'c'), | |
('a', 'a1'), | |
('a', 'a2'), | |
('a2', 'a21'), | |
('a2', 'a22'), | |
('b', 'b1'), | |
('b1', 'b11'), | |
('b11', 'b111'), | |
('b', 'b2'), | |
('c', 'c1'), | |
] | |
expected = { | |
'a': {'a1': {}, 'a2': {'a21': {}, 'a22': {}}}, | |
'b': {'b1': {'b11': {'b111': {}}}, 'b2': {}}, | |
'c': {'c1': {}}, | |
} | |
def to_tree(_input): | |
output = {} | |
for i, kv in enumerate(_input): | |
if kv[0] is None: | |
output[kv[1]] = {} | |
else: | |
def iterdict(d): | |
for k, v in d.items(): | |
if k == kv[0]: | |
d[k][kv[1]] = {} | |
return True | |
elif isinstance(v, dict): | |
ret = iterdict(v) | |
if ret is True: | |
return True | |
iterdict(output) | |
return output | |
assert to_tree(source) == expected |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment