How to Yield in a recursive function in Python

前端 未结 3 1478
孤独总比滥情好
孤独总比滥情好 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:56

    Note that you do not necessarily need to use yield:

    def last(d):
      c = [i for b in d.items() for i in ([b] if not isinstance(b[-1], dict) else last(b[-1]))]
      return c
    
    print(dict(last({'a': {'b': {'c': 'd', 'e': 'f'}}})))
    

    Output:

    {'c': 'd', 'e': 'f'}
    

提交回复
热议问题