I have a Python dictionary in the following form:
{
'a': {'leaf1': 12, 'leaf2': 32},
'b': {'a': 2, 'leaf3': 21, 'leaf4': 3},
'c': {'leaf5': 5, 'leaf6': 7}
}
where 'a', 'b', 'c' are internal nodes, and leaf1 ... leaf6 are leaf nodes(don't have children), and 12, 32, 2, 21, ... 7 are branch lengths of given node or subtree.
I need to convert this dictionary to Newick form in order to draw a tree using external applications.
Newick format:
(((leaf1:12,leaf2:32):2,leaf3:21, leaf4:3),leaf5:5,leaf6:7);
I wrote the following code, but without success:
def get_newick(self,dic):
roots=[node for node,children in dic.items() if sum([1 if len(child)>1 else 0 for child in children.keys()])==len(children.keys())]
nonrooted=[node for node,children in dic.items() if sum([1 if len(child)>1 else 0 for child in children.keys()])!=len(children.keys())]
dic1={}
for subtree in nonrooted:
patt=[]
for child,v in dic[subtree].items():
if child in roots:
patt.append(tuple(["%s:%d"%(k,v) for k,v in dic[child].items()]))
roots.remove(child)
elif len(child)>1:
patt.append("%s:%d"%(child,v))
dic1[subtree]=patt