I have a tree structure where at every node idf values are stored for a large number of words. Dictionary has two fields i.e. word and idf.
I want to store all the idf values in a dictionary. I want all the value of idf which are stored in the tree to get stored in the dictionary, but when I am doing so it is storing only one value of each word.
For example: A has two childs B and C. A,B,C all has idf values stored at them. I want to make a dictionary which will combine all the idf values and store it together.
A = {'a':10, 'b': 11} B = {'a':5, 'c': 8} C = {'b':21, 'd': 20}
, I want to store it as dic = {'a':10,'a':5,'b':11,'b':21,'c':8,'d':20}
Below is the code that I am using:
def idf_total(node):
dic={}
next_node=[]
for child in node.children:
next_node.append(child)
idf = child.idf
dic.update(idf)
if next_node:
for i in next_node:
idf_total(i)
return dic
Kindly help how this can be done.
Latest code:
def idf_total_updated(node):
dic=defaultdict(list)
next_node=[]
for child in node.children:
next_node.append(child)
for k,v in child.idf.items():
dic[k].append(v)
if next_node:
for i in next_node:
idf_total_updated(i)
return dic
The above latest code is storing multiple values for a key but it is repeating the same value again and again. Where I am going wrong. Please help.