Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: tree like implementation of dict datastructure [closed]

I have dict object something similar to like this,

topo = {
'name' : 'm0',
'children' : [{
    'name' : 'm1',
    'children' : []
 }, {
    'name' : 'm2',
    'children' : []
 }, {
    'name' : 'm3',
    'children' : []
 }]
}

Now, i want to insert one more dict object let's say,

{
'name' : 'ABC',
'children' : []
}

as child of dict named "m2" inside m2's children array.

Could you please suggest how should i go about it?

Should i go for a separate data structure implementation ?

like image 909
Aashish P Avatar asked Jun 14 '13 11:06

Aashish P


1 Answers

I would suggest you first convert it to a data structure like this:

topo = {
  'm0' : {
    'm1' : {},
    'm2' : {},
    'm3' : {},
  },
}

That is, you have made every value for the 'name' key be a key in a dictionary, and every value for the 'children' key be the value for that key, and changed it to a dictionary instead of a list.

Now you don't need to assume beforehand the index position where m2 is found. You do need to know that m2 is inside m0, but then you can simply say

topo['m0']['m2']['ABC'] = {}

You can convert between formats with this code:

def verbose_to_compact(verbose):
    return { item['name']: verbose_to_compact(item['children']) for item in verbose }

def compact_to_verbose(compact):
    return [{'name':key, 'children':compact_to_verbose(value)} for key, value in compact]

Call them like this

compact_topo = verbose_to_compact([topo]) # function expects list; make one-item list
verbose_topo = compact_to_verbose(compact_topo)[0] # function returns list; extract the single item

I am assuming the format you have is the direct interpretation of some file format. You can read it in that way, convert it, work with it in the compact format, and then just convert it back when you need to write it out to a file again.

like image 195
morningstar Avatar answered Sep 27 '22 22:09

morningstar