json - Python dictionary giving weird results -



json - Python dictionary giving weird results -

i trying generate inverted-index construction json response result.

[{"node":[{"node": [{"node": [{"id": "w"}], "id": "q"}], "id":"e"},{"id":"r"},{"id":"t"}],"id":"y"}, {"id": "u"}]

here sample json data, i'm trying maintain track of index of each 'id' object. illustration in given sample, object 'id' equal 'u' have index [1] , object 'id' equal 'q' have index [0[0[0]]].

resultant index representation here in form of array, [1] , [0,0,0] respectively.

i have written code all.

class="snippet-code-html lang-html prettyprint-override">class tree: def __init__(self, data): self.data = info self.indices = {} self.create_index(self.data) def create_index(self, data): in range(len(data)): self.trace_node(data[i], i, []) print self.indices def trace_node(self, node, index, index_list): _list = index_list _list.append(index) self.indices[node['id']] = _list print node['id'], _list try: in range(len(node['node'])): self.trace_node(node['node'][i], i, _list) except: pass

when run code, prints right result each node while tracing, @ end of execution indices class variable (dict object) left weird values , i'm unable figure out, why?

here result of execution, used above given json data in this.

tree = tree(data)

and prints :

y [0]

e [0, 0]

q [0, 0, 0]

w [0, 0, 0, 0]

r [0, 1]

t [0, 2]

u [1]

{'e': [0], 'q': [0], 'r': [0], 'u': [1], 't': [0], 'w': [0], 'y': [0]}

so can see here prints right resultant index array each 'id' @ end class variable indices showing, don't know what.

ps: don't believe in asking kind of personal problems i'm fighting since whole day. asked same friend , after time's fight, said seems fine me.

so i'm waiting reply , lesson larn :)

thanks in advance.

as pointed out in comment section, need re-create list.

just replace

self.indices[node['id']] = _list

with

self.indices[node['id']] = _list[:]

the reason seeing weird result that, nodes of same master tree branch getting same _list object assigned them. , since doing _list.pop(), final _list becomes list of top level index.

also,node['ch'] should node['node'] in code snippet. guess typing error :-)

python json class dictionary inverted-index

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -