I am new to python. I code below however I am hitting exception.
Input
studId=ValueA,studName=valueB;studId=ValueC,studName=ValueD
Output if list
[{'name':'ValueA','value':'valueB'},{'name':'ValueC','value':'valueD'}]
Output
ValueA
My code
str = "studId=ValueA,studName=valueB;studId=ValueC,studName=ValueD"
stud_list = dict(item.split("=") item.split(",") for item in str.split(";"))
for stud in stud_list :
print(stud['studName'])
exception
SyntaxError: invalid syntax
CodePudding user response:
Update the structure while loading the data
str = "studId=ValueA,studName=valueB;studId=ValueC,studName=ValueD"
stud_list = [dict(it.split("=") for it in item.split(",")) for item in str.split(";")]
for stud in stud_list :
print(stud['studName'])
CodePudding user response:
While I also enjoy comprehensions, more readably, one could:
inStr = "studId=ValueA,studName=valueB;studId=ValueC,studName=ValueD"
dict_list = []
for d in inStr.split(';'):
dict_list.append({})
for pair in d.split(','):
k, v = pair.split('=')
dict_list[-1][k] = v
print(dict_list)