递归遍历,返回路径和查找到的值
from collections import Mapping
def recursive_findall(obj, key, paths=None):
ret = []
if not paths:
paths = []
if isinstance(obj, Mapping):
for k, v in obj.iteritems():
found_items = recursive_findall(v, key, paths=(paths + [('k', k)]))
ret += found_items
elif isinstance(obj, (list, tuple)):
for i, v in enumerate(obj):
found_items = recursive_findall(v, key, paths=(paths + [('i', i)]))
ret += found_items
else:
if key(obj):
ret.append((paths, obj))
return ret
print recursive_findall(['a', 'bcd', {'bx': '33', 'cx': {'b': '34'}}], key=lambda v: '3' in v)
# [([('i', 2), ('k', 'cx'), ('k', 'b')], '34'), ([('i', 2), ('k', 'bx')], '33')]
# 'i'表示是list的index, 'k'表示是dict的key