递归访问嵌套字典的路径和值 [英] Recursively accessing paths and values of a nested dictionary

查看:96
本文介绍了递归访问嵌套字典的路径和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2.7中,如何动态访问并打印出嵌套字典的键和值?这是一个荒谬的示例: https://jsoneditoronline.org/?id=da7a486dc2e24bf8b94add9f04c71b4d

通常,我会做类似的事情:

import json

json_sample = 'sample_dict.json'
json_file = open(json_sample, 'r')
json_data = json.load(json_file)

items = json_data['sample_dict']

for item in items:
    dict_id = item['dict_id']
    person = item['person']['person_id']
    family = item['family']['members']

    print dict_id
    print person
    print family

我可以像这样对它进行硬编码,它将为我带来理想的结果,但是我将如何动态地访问每个键和值,以便:

  • 第一行仅打印键(dict_idperson['person_id']person['name']family['members']['father'])
  • 第二行分别打印值(5、15,"Martin","Jose")

最终结果应该在CSV文件中.

解决方案

您可以使用递归的访问者/生成器,该访问器/生成器返回叶子的所有路径/值对:

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])

(将yield from ...替换为适当的等效值(如果使用Python< 3.4)

获取密钥:

>>> ','.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'

和值:

>>> ','.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,[]'

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=da7a486dc2e24bf8b94add9f04c71b4d

Normally, I would do something like:

import json

json_sample = 'sample_dict.json'
json_file = open(json_sample, 'r')
json_data = json.load(json_file)

items = json_data['sample_dict']

for item in items:
    dict_id = item['dict_id']
    person = item['person']['person_id']
    family = item['family']['members']

    print dict_id
    print person
    print family

I can hard code it like this and it'll give me desirable results, but how would I access each of the keys and values dynamically so that:

  • The first row just prints the keys (dict_id, person['person_id'], person['name'], family['members']['father'])
  • The second row prints the values respectively (5, 15, "Martin", "Jose")

The end result should be in a CSV file.

解决方案

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,[]'

这篇关于递归访问嵌套字典的路径和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆