在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_id
,person['person_id']
,person['name']
,family['members']['father']
)最终结果应该是CSV文件。
答案 0 :(得分:2)
您可以使用递归访客/生成器返回叶子的所有路径/值对:
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])
(如果使用Python< 3.4),请将yield from ...
替换为appropriate equivalent
获取密钥:
>>> ','.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,[]'