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' """ifisinstance(x, dict):for v in x.values():yieldfrom into(v)elifisinstance(x, (tuple, list)):for v in x:yieldfrom 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 """ifisinstance(x, dict):return count +sum(into(v, count) for v in x.values())elifisinstance(x, (tuple, list)):return count +sum(into(v, count) for v in x)else:return count +1