Recursively accessing paths and values of a nested dictionary

后端 未结 1 668
耶瑟儿~
耶瑟儿~ 2021-01-03 07:53

In Python 2.7, how does one dynamically access and print out the keys and values of a nested dictionary? Here\'s a nonsensical example: https://jsoneditoronline.org/?id=da7a

相关标签:
1条回答
  • 2021-01-03 08:44

    You can use a recursive visitor/generator which returns all the path/value pairs of the leaves:

    def visit_dict(d, path=[]):
        for k, v in d.items():
            if not isinstance(v, dict):
                yield path + [k], v
            else:
                yield from visit_dict(v, path + [k])
    

    (replace the yield from ... with the appropriate equivalent if using Python < 3.4)

    Getting the keys:

    >>> ','.join('/'.join(k) for k, v in visit_dict(json_data['sample_dict'][0]))
    'dict_id,person/person_id,person/name,person/age,family/person_id,family/members/father,family/members/mother,family/members/son,family/family_id,items_id,furniture/type,furniture/color,furniture/size,furniture/purchases'
    

    and the values:

    >>> ','.join(str(v) for k, v in visit_dict(json_data['sample_dict'][0]))
    '5,15,Martin,18,20,Jose,Maddie,Jerry,2,None,Chair,Brown,Large,[]'
    
    0 讨论(0)
提交回复
热议问题