I like the stacks and functions of the generator:
def flatten(seq, *seq_types): stack = [iter(seq)] while stack: for item in stack[-1]: if isinstance(item, seq_types): stack.append(iter(item)) break else: yield item else: stack.pop() keys = [0, 1, (2, 3, [4.])] values = (5, 6, (7, "joe", [9])) print dict(zip(flatten(keys, list, tuple), flatten(values, tuple, list)))
Result:
{0: 5, 1: 6, 2: 7, 3: 'joe', 4.0: 9}
Or, if you know for sure that the input lists have the same structure, this may also work:
def flatten(seq, *seq_types): seq = list(seq) for item in seq: if isinstance(item, seq_types): seq.extend(item) else: yield item
Beware of reordering elements:
print list(flatten([1, 2, [3, 4, [5]]], list)) print list(flatten([1, 2, [[3, 4], 5]], list))
Result:
[1, 2, 3, 4, 5] [1, 2, 5, 3, 4]