dictionary - Reading intricated dictionaries in depth Python -
i have big dictionary smaller dictionaries inside, , i'm trying values inside aren't dictionaries (but strings, lists or integers), "path". tried use dfs (depth first search) techniques, without success. here sample of big dictionary :
{ 'visplanesection': { 'valuemode': 'single section', 'origininput': '[0.4, 1.3877787807814457e-17, -8.4350929019372245e-16] m,m,m', 'orientationinput': '[1.0, 0.0, -3.3133218391157016e-16] m,m,m', 'coordinatesystem': 'laboratory->reference', 'inputpartsinput': '[region]', 'valueindex': '-1', 'vissinglevalue': { 'valuequantityinput': '0.0 m' } }, 'childrencount': '2' }
the data need : visplanesection.valuemode = 'single section'
visplanesection.valuemode = 'single section'
visplanesection.origininput = [0.4, 1.3877787807814457e-17, -8.4350929019372245e-16] m,m,m
- ...ect...
- visplanesection.vissinglevalue.valuequantityinput = '0.0 m'
how should ? might tree discovery in depth issue, don't know how implement on problem.
[edit] : more specific, here's have today :
def test(dictio, path=[]): print(path) if type(dictio) == dict: k in dictio.keys(): if path == []: path.append(k) else: new_path = path[-1] + "." + k path.append(new_path) test(dictio[k], path) else: path.pop()
so, dictionary showed you, final element of each lists path want, not working :
[] ['visplanesection'] ['visplanesection', 'visplanesection.valuemode'] ['visplanesection', 'visplanesection.origininput'] ['visplanesection', 'visplanesection.orientationinput'] ['visplanesection', 'visplanesection.coordinatesystem'] ['visplanesection', 'visplanesection.inputpartsinput'] ['visplanesection', 'visplanesection.valueindex'] ['visplanesection', 'visplanesection.vissinglevalue'] ['visplanesection', 'visplanesection.vissinglevalue', 'visplanesection.vissinglevalue.valuequantityinput'] ['visplanesection', 'visplanesection.vissinglevalue', 'visplanesection.vissinglevalue.childrencount']
have here visplanesection.vissinglevalue.childrencount
instead of visplanesection.childrencount
last element, that's issue is.
patience , answers
you didn't mention python version you're using this, python 3.4+ better yield from
syntax , whatnot. here's came python 2.7:
def deconstruct(node, path=none): if not path: path = [] key, value in node.items(): if isinstance(value, dict): sub_value in deconstruct(value, path + [key]): yield sub_value else: yield (value, '.'.join(path + [key])) if __name__ == '__main__': value, path in deconstruct(input_dict): print path, '=', value
if execution speed concern - might want replace list string in path variable.
Comments
Post a Comment