How to Yield in a recursive function in Python

前端 未结 3 1487
孤独总比滥情好
孤独总比滥情好 2021-02-14 14:32

So I have a dictionary:

{\'a\': {\'b\': {\'c\': \'d\', \'e\': \'f\'}}}

I need to create a dictionary as follows:

{\'c\':\'d\',          


        
3条回答
  •  春和景丽
    2021-02-14 14:59

    Use yield from with your recursive call, otherwise you are just ignoring the result of the recursive call:

    def boil_down_array(key, data):
        if type(data) == dict:
            for key, item in data.items():
                yield from boil_down_array(key, item)
        else:
            yield {key: data}
    

    This is only available in Python > 3.3, but essentially just a short hand for simply yielding from an extra loop:

    for key, item in data.items():
        for x in boil_down_array(key, item):  # just exhaust the recursive generator
            yield x  # and "re-yield" what it produces
    

    In order to achieve your desired data structure, you might be better off yielding pairs instead of dicts, so you can transform the result more easily to the resulting dict:

    yield key, data
    

    Then you can use it like:

    result = dict(boil_down_array(None, input_dict))
    

    An even simpler recursive approach will just return a complete dict:

    def boil_down_nested(dct):
        result = {}
        for k, v in dct.items():
            if isinstance(v, dict):
                result.update(boil_down_nested(v))
            else:
                result[k] = v
        return result
    

提交回复
热议问题