input_string='aa = 2, bb = [{"hh":"dd"},{"hh":"dd"}], cc = 2020-07-08 ,10AM'
ll=input_string.split(',')
parsed=[]
for i in range(len(ll)):
if '=' not in ll[i]:
latest_index_with_equal=i
while True:
if latest_index_with_equal>=0:
if '=' in ll[latest_index_with_equal-1]:
break
else:
latest_index_with_equal-=1
else:
break
parsed.append(ll[latest_index_with_equal-1]+ll[i])
else:
if '=' in ll[i+1]:
parsed.append(ll[i])
parsed_=[]
for i in range(len(parsed)):
parsed[i]=parsed[i].replace('}{','},{')
if ('{' not in parsed[i] or '[' not in parsed[i]) or (parsed[i].split('=')[-1].replace(' ','')[0] == '[' and parsed[i].split('=')[-1].replace(' ','')[-1] == ']' or parsed[i].split('=')[-1].replace(' ','')[0] == '{' and parsed[i].split('=')[-1].replace(' ','')[-1] == '}'):
if parsed[i][0]==' ':
parsed[i]=parsed[i][1:]
parsed_.append(parsed[i])
out_={}
for i in parsed_:
key=i.split('=')[0]
if key[-1]==' ':
key=key[:-1]
value=i.split('=')[-1]
if value[-1]==' ':
value=value[:-1]
if value[0]==' ':
value=value[1:]
if (value[0] == '[' and value[-1] == ']') or (value[0] == '{' and value[-1] == '}'):
value=eval(value)
elif value.isdigit():
value=int(value)
else:
value=str(value)
out_[key]=value
print(out_)
Вывод:
{'aa': 2, 'bb': [{'hh': 'dd'}, {'hh': 'dd'}], 'cc': '2020-07-08 10AM'}