我想拆分键和值并显示下面提到的格式的字典结果。我正在读取一个文件并将数据拆分为列表,然后再转到字典。
请帮助我得到结果。
输入文件- commands.txt
login url=http://demo.url.net username=test@url.net password=mytester
create-folder foldername=demo
select-folder foldername=test123
logout
预期结果格式
print result_dict
"0": {
"login": [
{
"url": "http://demo.url.net",
"username": "test@url.net",
"password": "mytester"
}
]
},
"1": {
"create-folder": {
"foldername": "demo"
}
},
"2": {
"select-folder": {
"foldername": "test-folder"
}
},
"3": {
"logout": {}
}
代码
file=os.path.abspath('catalog/commands.txt')
list_output=[f.rstrip().split() for f in open(file).readlines()]
print list_output
counter=0
for data in list_output:
csvdata[counter]=data[0:]
counter=counter+1
print csvdata
for key,val in csvdata.iteritems():
for item in val:
if '=' in item:
key,value=item.split("=")
result[key]=value
print result