from pprint import pprint
from collections import defaultdict
# one-line definition of a tree:
def tree(): return defaultdict(tree)
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']
def dicts(t): return {k: dicts(v) for k,v in t.iteritems()}
def print_tree(t): pprint(dicts(t))
print_tree(taxonomy)
# {'Animalia': {'Chordata': {'Mammalia': {'Carnivora': {'Canidae': {'Canis': {'coyote': {},
# 'dog': {}}},
# 'Felidae': {'Felis': {'cat': {}},
# 'Panthera': {'lion': {}}}}}}},
# 'Plantae': {'Solanales': {'Convolvulaceae': {'Ipomoea': {'sweet potato': {}}},
# 'Solanaceae': {'Solanum': {'potato': {},
# 'tomato': {}}}}}}
class Tree < Hash
def initialize
super{|hash, key| hash[key] = Tree.new }
end
end
taxonomy = Tree.new
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]
require "pp"
pp taxonomy.inspect
# {:animalia=>
# {:chordata=>
# {:mammalia=>
# {:carnivora=>
# {:felidae=>{:felis=>{:cat=>{}}, :panthera=>{:lion=>{}}},
# :canidae=>{:canis=>{:dog=>{}, :coyote=>{}}}}}}},
# :plantae=>
# {:solanales=>
# {:solanaceae=>{:solanum=>{:tomato=>{}, :potato=>{}}},
# :convolvulaceae=>{:ipomoea=>{:sweet_potato=>{}}}}}}