Skip to content

Instantly share code, notes, and snippets.

@rg3915
Created March 9, 2016 12:16
Show Gist options
  • Select an option

  • Save rg3915/5f3fe2adb9db9c098dd4 to your computer and use it in GitHub Desktop.

Select an option

Save rg3915/5f3fe2adb9db9c098dd4 to your computer and use it in GitHub Desktop.
Transform list of urls in dict structured
urls = [
"/foo/",
"/foo/bar",
"/foo/bar/baz",
"/foo/bar/bez",
"/foo/bar/biz",
"/foo/ber",
"/foo/ber/baz",
"/foo/ber/bez",
"/foo/ber/biz",
]
def acha_filho(pai, nome):
for filho in pai["filhos"]:
if filho["nome"] == nome:
return filho
filho = {"nome": nome, "filhos": []}
pai["filhos"].append(filho)
return filho
raiz = {"nome": "raiz", "filhos": []}
for url in urls:
partes = url.strip('/').split('/')
pai = raiz
for parte in partes:
pai = acha_filho(pai, parte)
raiz
def imprime_no(no, nivel=0):
print("." * nivel, no["nome"])
for filho in no["filhos"]:
imprime_no(filho, nivel + 1)
imprime_no(raiz)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment