This will work with nested iterators of a different type than dict, if properly configured:
'Prototypes' :
def should_iter_fnc(it): """returns 'True' if 'it' is viewed as nested""" raise NotImplementedError def join_fnc(itr): """transform an iterable 'itr' into appropriate object""" raise NotImplementedError def values_fnc(itr): """get the list of 'values' of interest from iterable 'itr'""" raise NotImplementedError
Function itself
def recursive_join(smth, join_fnc, should_iter_fnc, values_fnc): if should_iter_fnc(smth): return join_fnc([ recursive_join(it, join_fnc, should_iter_fnc, values_fnc) for it in values_fnc(smth) ]) else: return smth
<i> gives:
>>> def should_iter(it): """Returns 'True', if 'it' is 'iterable' but not an 'str' instance""" if isinstance(it, str): return False try: iter(it) return True except TypeError: return False >>> print recursive_join(smth=[['1','2'],['3','4'],'5'], join_fnc=lambda itr: ' '.join(itr), should_iter_fnc=should_iter, values_fnc=list) 1 2 3 4 5 >>> print recursive_join(smth={1:{1:'1',2:'2'},2:{3:'3',4:'4'},3:'5'}, join_fnc=lambda itr: ' '.join(itr), should_iter_fnc=should_iter, values_fnc=lambda dct:dct.values()) 1 2 3 4 5
source share