如果您不知道键将出现在哪个深度,则需要遍历整个字典。
我很自由,可以将您的数据转换为实际有序的字典。如果相同的键出现在不同的子目录中,该函数可能会产生多个结果:
from collections import OrderedDict
mydict = OrderedDict ( {'KYS_Q1AA_YouthSportsTrustSportParents_P':
OrderedDict ( {'KYS_Q1AA':
OrderedDict ( [ ('chart_layout', '3'),
('client_name', 'Sport Parents (Regrouped)'),
('sort_order', 'asending'),
('chart_type', 'pie'),
('powerpoint_color', 'blue'),
('crossbreak', 'Total')
] ) } ) } )
def listRecursive (d, key):
for k, v in d.items ():
if isinstance (v, OrderedDict):
for found in listRecursive (v, key):
yield found
if k == key:
yield v
for found in listRecursive (mydict, 'powerpoint_color'):
print (found)
如果您对在哪里找到密钥感兴趣,可以相应地调整代码:
def listRecursive (d, key, path = None):
if not path: path = []
for k, v in d.items ():
if isinstance (v, OrderedDict):
for path, found in listRecursive (v, key, path + [k] ):
yield path, found
if k == key:
yield path + [k], v
for path, found in listRecursive (mydict, 'powerpoint_color'):
print (path, found)