Python Split dynamic string to key value pairs

i need some help.
I have dynamic string like this:

S31
S4
S2M1L10XL8
S1M2L0XL0
S0M5L6XL8

and need change it to key value like:

{"S":31}
{"S":4}
{"S":2, "M":1, "L":10, "XL":8}
{"S":1, "M":2, "L":0, "XL":0}
{"S":0, "M":5, "L":6, "XL":8}

I try with

new_string = re.findall('(\d+|[A-Za-z]+)', string)

but can't find hoe to solve

Upvotes: 0

Views: 424

Answers (3)

L8Cod3r
L8Cod3r

Reputation: 92

Try this:

dict(re.findall('(\D+)(\d+)',your_string))
>>> s = "S2M1L10XL8"
>>> re.findall('(\D+)(\d+)',s)
[('S', '2'), ('M', '1'), ('L', '10'), ('XL', '8')]

1st Capturing Group (\D+) \D matches any character that's not a digit (equivalent to [^0-9])

  • matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)

2nd Capturing Group (\d+) \d matches a digit (equivalent to [0-9])

  • matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)

https://regex101.com/r/hww2rm/1

Upvotes: 1

Barmar
Barmar

Reputation: 782099

The regexp should match letters followed by numbers, not letters or numbers. Put them each in a separate capture group. You can then iterate over that and use a dictionary comprehension to

new_dict = {name.upper(): int(num) for name, num in re.findall(r'([A-Z]+)(\d+)', string, flags=re.I)}

Upvotes: 1

Kelly Bundy
Kelly Bundy

Reputation: 27629

Your regex usage is alright, here's one way to make it work:

it = iter(re.findall('(\d+|[A-Za-z]+)', string))
result = dict(zip(it, map(int, it)))

Upvotes: -1

Related Questions