Traversing leaf nodes

Get ‘leaves’ traversing multilevel structure of dicts and iterables (yield from expr inspiration/demo)

.py
# { 1: 11,
#   2: [21, 22, 23],
#   3: {31: ['a', 'b', 'c']}
#   } ->  11, 21, 22, 23, 'a', 'b', 'c'

def into(x):
    """ Travesal through hierarchical structures, returning 'leaves' """
    if isinstance(x, dict):
        for v in x.values():
            yield from into(v)
    elif isinstance(x, (tuple, list)):
        for v in x:
            yield from into(v)
    else:
        yield x
# pre-3.3 variation for _counting_ leaves
# (since 'yield from <expr>' appears in Python 3.3)

def into(x, count=0):
    """ 
    Count leaves traversing multilevel structure of dicts and iterables
    All the simple typed values and only nonempty containers are counted
    """
    if isinstance(x, dict):
        return count + sum(into(v, count) for v in x.values())
    elif isinstance(x, (tuple, list)):
        return count + sum(into(v, count) for v in x)
    else:
        return count + 1