Python is used to demonstrate the data structure of a number.
The defaultdict Method built in Python allows you to easily define the data structure of a tree.
In short, a tree can also be a dictionary data structure.
def tree(): return defaultdict(tree)
This is all, just a line of code.
If you continue the following code, you must first introduce
from collections import defaultdict
Instance
JSON-esque
Now we can create a JSON-esque nested dictionary without explicitly creating a subdictionary:
users = tree()users['harold']['username'] = 'hrldcpr'users['handler']['username'] = 'matthandlersux'
You can then print json data using <code> print (JSON. dumps (users) </code>. The result is as follows:
{"harold": {"username": "hrldcpr"}, "handler": {"username": "matthandlersux"}}
No value assignment required
We can create a structure without assigning values:
taxonomy = tree()taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Felidae']['Felis']['cat']taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Felidae']['Panthera']['lion']taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Canidae']['Canis']['dog']taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Canidae']['Canis']['coyote']taxonomy['Plantae']['Solanales']['Solanaceae']['Solanum']['tomato']taxonomy['Plantae']['Solanales']['Solanaceae']['Solanum']['potato']taxonomy['Plantae']['Solanales']['Convolvulaceae']['Ipomoea']['sweet potato']
To print good information, you need to convert it into a standard dictionary object:
def dicts(t): return {k: dicts(t[k]) for k in t}
Now you can print it through pprint (dicts (taxonomy:
{'Animalia': {'Chordata': {'Mammalia': {'Carnivora': {'Canidae': {'Canis': {'coyote': {}, 'dog': {}}}, 'Felidae': {'Felis': {'cat': {}}, 'Panthera': {'lion': {}}}}}}}, 'Plantae': {'Solanales': {'Convolvulaceae': {'Ipomoea': {'sweet potato': {}}}, 'Solanaceae': {'Solanum': {'potato': {}, 'tomato': {}}}}}}
Sub-structures are also considered as Dictionary objects, while leaf nodes are empty dictionary objects.
Iteration
You can use interesting methods to iterate the tree.
For example, if We parse an animal list and add it to the previously defined taxonomy, we can use the following code:
add(taxonomy, 'Animalia,Chordata,Mammalia,Cetacea,Balaenopteridae,Balaenoptera,blue whale'.split(','))
Simplified Implementation:
def add(t, keys): for key in keys: t = t[key]
We still do not need to assign values:
{'Animalia': {'Chordata': {'Mammalia': {'Carnivora': {'Canidae': {'Canis': {'coyote': {}, 'dog': {}}}, 'Felidae': {'Felis': {'cat': {}}, 'Panthera': {'lion': {}}}}, 'Cetacea': {'Balaenopteridae': {'Balaenoptera': {'blue whale': {}}}}}}}, 'Plantae': {'Solanales': {'Convolvulaceae': {'Ipomoea': {'sweet potato': {}}}, 'Solanaceae': {'Solanum': {'potato': {}, 'tomato': {}}}}}}
Conclusion
These mentioned above may be of little use, but they just made some interesting code.
If you like Python, think of it as fun to understand.