It is quite hard to parse the string but let us assume the pattern in the string is:
'\D+ : \d+ \D+ : \d+'
where \D
is a character and \d
is a digit and divided by :
, you may proceed as follows.
- Sanitize the string and replace
=
with :
- find all patterns for '\D+ : \d '
- loop over the found pattern and convert to a dict
for example
import re
input_str = "Car : 100 Bus: 200 Travel cost = 500 cycle : 10 bike : 50 "
input_str = input_str.replace('=', ':')
dict_elements = re.findall(r'\D+ : \d+ ', input_str)
my_dict = {}
for element in dict_elements:
key, val = element.split(':')
key = key.strip()
val = int(val.strip())
my_dict[key] = val
print(my_dict)
actually a better solution dealing with possible spaces before and after the : is the following
import re
input_str = "Car:100 Bus: 200 Travel cost = 500 cycle: 10 bike :50 "
dict_elements = re.findall(r'\s*(\D+)\s*[:=]\s*(\d+)\s*', input_str)
my_dict = {}
for element in dict_elements:
my_dict[element[0].strip()] = int(element[1].strip())
print(my_dict)
Note I dealt with :
or =
in the search string of findall with [:=], while key is (\D+) and val is (\d+).