I wrote a program sometime ago that reads csv files, sorts, reorders and groups their columns/rows' content (with itertools) and later labels the groups using a dictionary. The groups and dictionary are then flattened and rows of length N (columns) are uploaded to a spreadsheet. This is another function, not specific to that program, to use in this situation.
def digfrom(iterable, *, depth=None, strings=True):
"""
Dig values from nested iterables, flattening
the input iterable.
>>> iterable = [['a'], 'bc', ('de', ['f'])]
>>> list(digfrom(iterable))
['a', 'b', 'c', 'd', 'e', 'f']
Depth may be limited and "exploding" strings
is optional.
>>> list(digfrom(iterable, depth=2))
['a', 'b', 'c']
>>> list(digfrom(iterable, strings=False))
['a', 'bc', 'de', 'f']
"""
exhausted = object()
iterable_attr = '__iter__'
iterator_attr = '__next__'
iterators = [iter(iterable)]
while iterators:
it = next(iterators[-1], exhausted)
if it is exhausted:
iterators.pop()
continue
if hasattr(it, iterable_attr):
string = isinstance(it, str)
if not ((string and len(it) <= 1) or
(string and not strings)):
it = iter(it)
if hasattr(it, iterator_attr):
iterators.append(it)
iterators = iterators[:depth]
else:
yield it