You may use below regex
expressions to extract the required values from the string. Here's the one-liner to get the desired dict
:
>>> import re
>>> my_str = "item SHIRT 11-14 variance 11-12-13-14-15 color Red"
>>> keys = ["shirt", "variance", "color"]
>>> {k: v.split('-') if '-' in v else v for k, v in zip(keys, re.findall(
'(?<=SHIRT\s)[\d-]+|(?<=variance\s)[\d-]+|(?<=color\s)\w+',my_str))}
which will return the dict
object as:
{'color': 'Red', 'variance': ['11', '12', '13', '14', '15'], 'shirt': ['11', '14']}
Explanation of each regex pattern:
# For shirt:
# This regex matches the number and hyphen "-"
# preceded by "variance" and space " "
>>> re.search('(?<=SHIRT\s)[\d-]+', my_str).group()
'11-14'
# For variance:
# Same as the above regex, it matches the number and hyphen "-"
# preceded by "SHIRT" and space " "
>>> re.search('(?<=variance\s)[\d-]+', my_str).group()
'11-12-13-14-15'
# For color:
# This regex matches the alphabets followed by "color" and space " "
>>> re.search('(?<=color\s)\w+', my_str).group()
'Red'
Using this you can assign each key individually to your dict
explicitly too.
item SHIRT
,variance
,color
part ?