Created
March 9, 2016 12:16
-
-
Save rg3915/5f3fe2adb9db9c098dd4 to your computer and use it in GitHub Desktop.
Transform list of urls in dict structured
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
| 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