1

I have to parse a data source:

my_string = "Alex - 30% / Bob - 23.33%"

Here my_string contains two names but it could also be one person in length or three.

I want to obtain a dictionary mapping the names to the values:

result = {'Alex': 30, 'Bob': 23.33}

I've tried multiple approaches, such as regular expressions and splitting the string, but I just can't seem to crack this one.

6 Answers 6

3

Use re.findall():

>>> import re
>>> my_string = "Alex - 30% / Bob - 23.33%"
>>> r = re.findall(r'([a-zA-Z]*) - (\S+)%', my_string)
>>> r
[('Alex', '30'), ('Bob', '23.33')]

You can then create a dictionary:

>>> result = {name:float(val) for name,val in r}
>>> result
{'Alex': 30.0, 'Bob': 23.33}
Sign up to request clarification or add additional context in comments.

Comments

2

Try str.split

Split first on the / to get a list of your names. Then split each item of the list by - to get your individual fields.

Example:

finalDict = {}
values = my_string.split(" / ")
for(item in values):
    entry = item.split(" - ")
    finalDict[entry[0]] = float(entry[1].strip("%")) #if you want second field as a float

Comments

1

You may try this,

>>> my_string = "Alex - 30% / Bob - 23.33%"
>>> {i.split(' - ')[0]:float(i.split(' - ')[1].rstrip('%')) for i in my_string.split(' / ') }
{'Bob': 23.33, 'Alex': 30.0}

or

>>> s = my_string.split(' / ')
>>> {i.split(' - ')[0]:float(i.split(' - ')[1].rstrip('%')) for i in s}
{'Bob': 23.33, 'Alex': 30.0}

Comments

1
{name: float(value[:-1]) for name, value in (person.split(' - ') for person in my_string.split(' / '))}

2 Comments

You don't need to call tuple
@PadraicCunningham Thanks. Edited.
0

You can use str.split repeatedly:

my_string = "Alex - 30% / Bob - 23.33%"
result = dict([(s.split()[0],s.split()[2][:-1]) for s in my_string.split('/')])

The first parses based on the '/', and the second parses based on the '-'

Comments

0

Maybe you'd find it useful:

dict(substring.split(' - ') for substring in string.split(' / '))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.