Skip to content

Instantly share code, notes, and snippets.

@quatrix
Created June 13, 2016 17:10
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 quatrix/46cb8970de2948eda1c69fa8bad32cfc to your computer and use it in GitHub Desktop.
Save quatrix/46cb8970de2948eda1c69fa8bad32cfc to your computer and use it in GitHub Desktop.
import json
def flatten(n):
while True:
changed = False
for k, v in n.iteritems():
if len(v.keys()) == 1:
del n[k]
vk = v.keys()[0]
n[k + '/' + vk] = v[vk]
changed = True
else:
flatten(v)
if not changed:
break
return n
class Tree(object):
def __init__(self):
self.root = {}
def add(self, url):
r = self.root
for p in url.split('/'):
if p not in r:
r[p] = {}
r = r[p]
if __name__ == '__main__':
urls = [
'blog/a/a/a',
'blog/a/a/b',
'blog/a/b/a',
'blog/a/c/a',
'blog/a/d',
'blog/a/d/e',
]
t = Tree()
map(t.add, urls)
print(json.dumps(flatten(t.root), indent=2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment