递归查找小练习

递归小练习

#!/usr/bin/env/python
#-*- coding:utf-8 -*-

def findkeyvalue(keyname,target):
"""
使用递归方式在字典列表混合数据中查找指定key的值
只返回第一个符合的键值
find the first key's value in mix dict and list via recursion
:param keyname: key name (string)
:param tagetr: data (dict or list or both)
:return: the key's value
"""
    if isinstance(target,dict) and keyname in target:
        return target[keyname]
    if isinstance(target,dict) and keyname not in target:
        target = list(target.values())
    if isinstance(target,list):
        for i in target:
            if isinstance(i,dict) or isinstance(i,list):
                value = findkeyvalue(keyname,i)
                if value is not None:
                    return value
if __name__ == '__main__':

    bb = [
        [1, 2, 3, 4],
        [{'a': 'a', 'b': 'b'}, [12, 3], {'c': 1, 'd': [1, 2, {'e': [{'c': 1}]}, 4]}],
        {'a': {'a': {'a': 1}}, 'b': [432, 54]},
        [{'a': 1}, {'b': 2}, [{'c': 3}, {'a': 'cc', 'b': [1, {'cici': 'check'}]}]],
        [3, 4, 5],
        {'cici': 'bb'}
    ]
    print(findkeyvalue('cici', bb))
posted @ 2017-07-06 14:20  村口王铁匠  阅读(319)  评论(0编辑  收藏  举报