Using itertools.groupby and some iterators:
>>> from itertools import groupby >>> it = (next(g) if k else map(int, g) for k, g in groupby(x, str.isalpha)) >>> {k: next(it) for k in it} {'a': [3, 4], 'c': [4, 5], 'b': [1, 2]}
Here the first iterator will give something like:
>>> [next(g) if k else map(int, g) for k, g in groupby(x, str.isalpha)] ['a', [3, 4], 'b', [1, 2], 'c', [4, 5]]
Now, when this iterator will give the key-value alternately, we can iterate over this iterator and get the next element (i.e. value) from it using next()
>>> it = (next(g) if k else map(int, g) for k, g in groupby(x, str.isalpha)) >>> for k in it: print k,'-->' ,next(it) ... a --> [3, 4] b --> [1, 2] c --> [4, 5]
There's another way to use this iterator that uses zip , but it's a little hard to understand . IMO:
>>> it = (next(g) if k else map(int, g) for k, g in groupby(x, str.isalpha)) >>> dict(zip(*[it]*2)) {'a': [3, 4], 'c': [4, 5], 'b': [1, 2]}