Skip to content

Instantly share code, notes, and snippets.

@XCanG
Created January 30, 2020 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XCanG/17a7f3999674a9aa4457074bc1beae1f to your computer and use it in GitHub Desktop.
Save XCanG/17a7f3999674a9aa4457074bc1beae1f to your computer and use it in GitHub Desktop.
Convert dict pairs to dict tree
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