split string into list of tuples?

Question:

I have a string of key-value pairs, which unfortunately are separated by the same symbol. Is there a way to “just split” it into a list of tuples, without using a lambda?

Here is what i have:

Moscow|city|London|city|Royston Vasey|vilage

What i want:

[("Moscow","city"), ("London", "city")....] 
Asked By: Ibolit

||

Answers:

This is a pretty easy one really…

first, split the string on '|' then zip every other element together:

data = s.split('|')
print zip(data[::2],data[1::2])

In python3, you’ll need: print(list(zip(data[::2],data[1::2]))

Answered By: mgilson
def group(lst, n):
    for i in range(0, len(lst), n):
        val = lst[i:i+n]
        if len(val) == n:
            yield tuple(val)

a = 'Moscow|city|London|city|Royston Vasey|vilage'
list(group(a.split('|'), 2))

The output is [('Moscow', 'city'), ('London', 'city'), ('Royston Vasey', 'vilage')]

Answered By: imkost
s = 'Moscow|city|London|city|Royston Vasey|vilage'

it = iter(s.split('|'))
print [(x,next(it)) for x in it]
Answered By: eyquem

Python3:

>>> s = "Moscow|city|London|city|Royston Vasey|vilage"
>>> list(zip(*[iter(s.split('|'))]*2))
[('Moscow', 'city'), ('London', 'city'), ('Royston Vasey', 'vilage')]

Python2:

zip(*[iter(s.split('|'))]*2)
Answered By: John La Rooy

You could use city, status, remaining = s.split("|", 2) and some recursive method city_split(s) to achieve what you want.

Answered By: El Bert
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.