dictionary - convert a list of delimited strings to a tree/nested dict, using python -
i trying convert list of dot-separated strings, e.g.
['one.two.three.four', 'one.six.seven.eight', 'five.nine.ten', 'twelve.zero']
into tree (nested lists or dicts - easy walk through). real data happens have 1 4 dot-separated parts of different length , has 2200 records in total. actual goal fill in set of 4 qcombobox'es data, in manner 1st qcombobox filled first set items ['one', 'five', 'twelve'] (no duplicates). depending on chosen item, 2nd qcombobox filled related items: 'one' be: ['two', 'six'], , on, if there's nested level.
so far i've got working list -> nested dicts solution, it's horribly slow, since use regular dict(). , seem have trouble redesign defaultdict in way work out filling comboboxes properly.
my current code:
def list2tree(m): tmp = {} in range(len(m)): if m.count('.') == 0: return m = m.split('.', 1) try: tmp[a[0]].append(list2tree(a[1])) except (keyerror, attributeerror): tmp[a[0]] = list2tree(a[1]) return tmp main_dict = {} = 0 m in methods: main_dict = list2tree(m) += 1 if (i % 100) == 0: print i, len(methods) print main_dict, i, len(methods)
ls = ['one.two.three.four', 'one.six.seven.eight', 'five.nine.ten', 'twelve.zero'] tree = {} item in ls: t = tree part in item.split('.'): t = t.setdefault(part, {})
result:
{ "twelve": { "zero": {} }, "five": { "nine": { "ten": {} } }, "one": { "six": { "seven": { "eight": {} } }, "two": { "three": { "four": {} } } } }
Comments
Post a Comment