I would like convert my python dictionary, that contain a tree, in a HTML list that use the
I would like add one checkbox for each elements with the id= name of the elements + name of the dad
this is an example of my python dictionary:
{'Animalia': {'Chordata': {'Mammalia': {'Carnivora': {'Canidae': {'Canis': {'coyote': {},
'dog': {}}},
'Felidae': {'Felis': {'cat': {}},
'Panthera': {'lion': {}}}}}}},
'Plantae': {'Solanales': {'Convolvulaceae': {'Ipomoea': {'sweet potato': {}}},
'Solanaceae': {'Solanum': {'potato': {},
'tomato': {}}}}}}
And I would like obtain:
- Animalia
- Chordata
- convolvulacee
- Chordata
There is an easy way, to do this in python? Thank you
解决方案
A trivial couple of tweaks to the answer that you referenced will give you the result that you want:
def printItems(dictObj, parent, indent):
if len(dictObj):
print '{}
- '.format(' ' * indent)
for k,v in dictObj.iteritems():
print '{}
{}'.format(' ' * (indent+1), k, parent, k)
printItems(v, k, indent+1)
print '{}
'.format(' ' * indent)The tweak was to also pass the parent key to printItems() so that it can be included in the id attribute for the tag. The other change was to remove the leaf node processing because your leaves are denoted by an empty dictionary.
For input:
taxonomy = {
'Animalia': {
'Chordata': {
'Mammalia': {
'Carnivora': {
'Canidae': {
'Canis': {
'coyote': {},
'dog': {}
}
},
'Felidae': {
'Felis': {
'cat': {}
},
'Panthera': {
'lion': {}
}
}
}
}
}
},
'Plantae': {
'Solanales': {
'Convolvulaceae': {
'Ipomoea': {
'sweet potato': {}
}
},
'Solanaceae': {
'Solanum': {
'potato': {},
'tomato': {}
}
}
}
}
}
The output of printItems(taxonomy, 'root', 0) is:
- Animalia
- Chordata
- Mammalia
- Carnivora
- Canidae
- Canis
- coyote
- dog
- Canis
- Felidae
- Felis
- cat
- Panthera
- lion
- Felis
- Canidae
- Carnivora
- Mammalia
- Chordata
- Plantae
- Solanales
- Convolvulaceae
- Ipomoea
- sweet potato
- Ipomoea
- Solanaceae
- Solanum
- tomato
- potato
- Solanum
- Convolvulaceae
- Solanales