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")....]
When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.
Method #1 : Using map() + int + split() + tuple() This method can be used to solve this particular task. In this, we just split each element of string and convert to list and then we convert the list to resultant tuple.
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]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With