I have a system which returns the output in the following format from command line. I am trying to parse this and convert it to dict in python. A delimiter is ":" in the whole command, I just split the text with "\\n" and then further split it with ":" and just keep append it to a dict, but it works fine if keys are unique but here in command output block of code is repeated. so not sure who should I parse and get all the values in a dict. Here job till length is a repeated block of code. can have dict inside a dict or list but not sure how to repeat.
for d in res.split("\n"):
r = d.split(':')
if len(r) == 2:
return_dict[r[0].strip()]=r[1].strip()
else:
continue
here it will over write the job data and will only have the last values. any points will be really helful.
first name : John last name : mathew Total : 10 Final cost : 7000 time : 2017-09-12 Result : Pass
jobs pending : 2
jobs completed : 4
job : 0
ID : 42
name : filter_pre
type : zzsbcfdcd
length : 750
name : gasVacume
type : adfadfadkfj
length : 8567
job : 100
ID : 43
name : filter
type : adfadf
length : 800
job : 100
ID : 15
name : csprt
type : adfa
length : 1000
If you want to keep duplicate keys then you should create a list of dictionaries. Change your code with this code given below.
final_list = []
for d in res.split("\n"):
return_dict = {}
r = d.split(':')
if len(r) == 2:
return_dict[r[0].strip()]=r[1].strip()
final_list.append(return_dict)
else:
continue
print final_list
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.