I'm not able to get the correct value from txt file onto dictionary list. I'm calling raw output of text file, read it line by line, remove white space and parse onto dictionary.
Please find txt file below which consists of product id and product name. Please take note, some of the data content in the file source is upside down..what i mean is product id come first before product name (not in sequence)...pls refer to sample data below
Product id: sq112
Prodname: ment-bar1
Product id: sq001
Prodname: jumw-cd12
Product id: mcc-hg921
Prodname: emq-vx02
Product id: mmc112
Prodname: ment-bar2
Product id: cx022
Prodname: mxx-21ed
Product id: vcb113
Prodname: emq-vx05
Prodname: trc-vc01
Product id: emx-21ee
This is the script use to get the id and name
file = open("prd1.txt")
data = file.readlines()
dict = {"ProdList":[]}
temp_dict ={}
for line in data:
line = line.replace('\n', '').strip()
line = line.split(':')
line = list(filter(None,line))
temp_dict["ID"] = line[0]
temp_dict["Name"] = line[1]
dict["ProdList"].append(temp_dict)
temp_dict = {}
print(dict)
The dict output generated as below
{'ProdList': [{'ID': 'Product id', 'Name': ' sq112'}, {'ID': 'Prodname',
'Name': ' ment-bar1'}, {'ID': 'Product id', 'Name': ' sq001'}, {'ID':
'Prodname', 'Name': ' jumw-cd12'}, {'ID': 'Product id', 'Name': ' mcc-
hg921'}, {'ID': 'Prodname', 'Name': ' emq-vx02'}, {'ID': 'Product id',
'Name': ' mmc112'}, {'ID': 'Prodname', 'Name': ' ment-bar2'}, {'ID':
'Product id', 'Name': ' cx022'}, {'ID': 'Prodname', 'Name': ' mxx-21ed'},
{'ID': 'Product id', 'Name': ' vcb113'}, {'ID': 'Prodname', 'Name': ' emq-
vx05'}]}
Expected output as follows
{'ProdList':[{'ID':'sq112','Name':' ment-bar1'},{'ID':'sq001','Name':'
jumw-cd12'},{'ID':'mcc-hg921','Name':' emq-vx02'}]}
I tried as suggested below
for i in range(0,len(data),2):
line = data[i].split(':')
nxt_line = data[i+1].split(':')
if 'id' in data[0]:
dict['ProdList'].append({'ID':line[1], 'Name': nxt_line[1]})
else:
dict['ProdList'].append({'ID':nxt_line[1], 'Name': line[1]})
Im getting output below
{'ProdList':[{'ID':' sq112\n','Name':' ment-bar1\n'},{'ID':'
sq001\n','Name':' jumw-cd12\n'},{'ID':' mcc-hg921\n','Name':' emq-vx02\n'},
{'ID':' mmc112\n','Name':' ment-bar2\n'},{'ID':' cx022\n','Name':' mxx-
21ed\n'},{'ID':' vcb113\n','Name':' emq-vx05\n'},{'ID':' trc-
vc01\n','Name':' emx-21ee \n'}]}
The last id and product name upside down... it should be ID: emx-21ee and Name: trc-vc01