From 3b282d338c7c32d666e8ab796989a6766dc18667 Mon Sep 17 00:00:00 2001 From: oskar Date: Mon, 29 Sep 2025 13:20:41 +0200 Subject: [PATCH] eduroam-prg-hf-1-5-62.net.univ-paris-diderot.fr 2025-9-29:13:20:41 --- python tree with defaultdicts.md | 50 +++++++++++++++----------------- 1 file changed, 24 insertions(+), 26 deletions(-) diff --git a/python tree with defaultdicts.md b/python tree with defaultdicts.md index 05a75dc6..1dc2f4ff 100644 --- a/python tree with defaultdicts.md +++ b/python tree with defaultdicts.md @@ -1,34 +1,32 @@ --- -description: | - ```python - from collections import defaultdict - from pprint import pprint - tree = lambda: defaultdict(tree) # arbre = dictionnaire contenant un arbre - example = tree() # création de l'arbre - example["A"]["A.1"] - example["A"]["A.2"]["A.2.1"] - example["B"]["B.1"] - def tree_to_dicts(tree): # transformer en vrai dictionnaire - return {key: tree_to_dicts(tree[key]) for key in tree} - pprint(tree_to_dicts(example)) - def add_path(tree, path): - for node in path: - tree = tree[node] - add_path(example, ["B", "B.2", "B.2.1"]) - add_path(example, "B>B.2>B.2.2".split(">")) - pprint(tree_to_dicts(example)) - ``` +up: [[python tips]] +link: "https://gist.github.com/hrldcpr/2012250" +author: [[harold cooper]] +tags: + - "#s/informatique/langage/python" --- -up::[[python tips]] -link::https://gist.github.com/hrldcpr/2012250 -author::[[harold cooper]] -title::"definir des [[structure de données.arbre|arbres]] avec les defaultdicts du module [[python module collections]]" -#s/informatique/langage/python - ----- Permet de définir la structure d'[[structure de données.arbre]] de manière simple, grace aux `defaultdicts` (module collections) +# Résumé +```python +from collections import defaultdict +from pprint import pprint +tree = lambda: defaultdict(tree) # arbre = dictionnaire contenant un arbre +example = tree() # création de l'arbre +example["A"]["A.1"] +example["A"]["A.2"]["A.2.1"] +example["B"]["B.1"] +def tree_to_dicts(tree): # transformer en vrai dictionnaire + return {key: tree_to_dicts(tree[key]) for key in tree} +pprint(tree_to_dicts(example)) +def add_path(tree, path): + for node in path: + tree = tree[node] +add_path(example, ["B", "B.2", "B.2.1"]) +add_path(example, "B>B.2>B.2.2".split(">")) +pprint(tree_to_dicts(example)) +``` # Définition ```python