D_P
D_P

Reputation: 862

How to make a list with a comma separated strings?

Here I have string like this.

Size:20,color:red,Size:20,color: pink,Size: 90,color:red,Size: 90,color: pink,

Now I want to convert into this format

[{'Size': '20','color':'red'}, {'Size': '20','color': 'pink'}, {'Size': '90','color':'red'}, {'Size': ' 90','color': 'pink'}]

Can we make a list like this ?

Upvotes: 0

Views: 177

Answers (2)

Bruno Vermeulen
Bruno Vermeulen

Reputation: 3455

Another solution using re.findall you can get the list of dicts

import re

my_string = 'Size:20,color:red,Size:20,color: pink,Size: 90,color:red,Size: 90,color: pink,'
pattern = r'\s*?Size:(.*?),\s*?color:(.*?)(?:,|$)'

size_color_list = [{'Size': int(size), 'color': color.strip()}
                   for size, color in re.findall(pattern, my_string)]

print(size_color_list)

Slightly modified converting the size from a string to an int.

Upvotes: 0

Alex Hall
Alex Hall

Reputation: 36013

import re

text = "Size:20,color:red,Size:20,color: pink,Size: 90,color:red,Size: 90,color: pink,"

# Remove al whitespace
text = re.sub(r"\s+", "", text)

# Use named capture groups (?P<name>) to allow using groupdict
pattern = r"Size:(?P<Size>\d+),color:(?P<color>\w+)"

# Convert match objects to dicts in a list comprehension
result = [
    match.groupdict()
    for match in re.finditer(pattern, text)
]

print(result)

Upvotes: 3

Related Questions