I have below content as output.
['{end_date=2021-09-16 06:00:00, number=CHG1757, requested_by=Tom, cmdb_ci=Checkout, start_date=2021-09-16 03:00:00}',
'{end_date=2021-09-16 09:00:00, number=CHG17486, requested_by=Bobby, cmdb_ci=Reservation, start_date=2021-09-16 03:00:00}',
'{end_date=2021-09-16 12:00:00, number=CHG17441, requested_by=Ryan, cmdb_ci=Payment, start_date=2021-09-16 03:00:00}']
Need to convert above output to structured list of dictionaries(see below) using python script.
[{'end_date'='2021-09-16 06:00:00', 'number'='CHG1757', 'requested_by'='Tom', 'cmdb_ci'='Checkout', 'start_date'='2021-09-16 03:00:00'}',
{'end_date'='2021-09-16 09:00:00', 'number'='CHG17486', 'requested_by'='Bobby', 'cmdb_ci'='Reservation', 'start_date'='2021-09-16 03:00:00'}',
{'end_date'='2021-09-16 12:00:00', 'number'='CHG17441', 'requested_by'='Ryan', 'cmdb_ci'='Payment', 'start_date'='2021-09-16 03:00:00'}']
CodePudding user response:
Praful, how are you doing?
You can try use code below, but only will work if all strings have the same length.
stack = ['{end_date=2021-09-16 06:00:00, number=CHG1757, requested_by=Tom, cmdb_ci=Checkout, start_date=2021-09-16 03:00:00}',
'{end_date=2021-09-16 09:00:00, number=CHG17486, requested_by=Bobby, cmdb_ci=Reservation, start_date=2021-09-16 03:00:00}',
'{end_date=2021-09-16 12:00:00, number=CHG17441, requested_by=Ryan, cmdb_ci=Payment, start_date=2021-09-16 03:00:00}']
splited = []
for line in stack:
splited.append(line.split(','))
dict_to_fill = {}
new_list = []
for item in splited:
dict_to_fill['end_date'] = item[0][10:]
dict_to_fill['number'] = item[1][8:]
dict_to_fill['requested_by'] = item[2][14:]
dict_to_fill['cmdb_ci'] = item[3][9:]
dict_to_fill['start_date'] = item[4][12:-1]
new_list.append(dict_to_fill.copy())
print(new_list)
OUTPUT:
[{'end_date': '2021-09-16 06:00:00',
'number': 'CHG1757',
'requested_by': 'Tom',
'cmdb_ci': 'Checkout',
'start_date': '2021-09-16 03:00:00'},
{'end_date': '2021-09-16 09:00:00',
'number': 'CHG17486',
'requested_by': 'Bobby',
'cmdb_ci': 'Reservation',
'start_date': '2021-09-16 03:00:00'},
{'end_date': '2021-09-16 12:00:00',
'number': 'CHG17441',
'requested_by': 'Ryan',
'cmdb_ci': 'Payment',
'start_date': '2021-09-16 03:00:00'}]
Tell me if worked.
See ya!
CodePudding user response:
Please find below the dynamic code to solve your issue:
stack = ['{end_date=2021-09-16 06:00:00, number=CHG1757, requested_by=Tom, cmdb_ci=Checkout, start_date=2021-09-16 03:00:00}',
'{end_date=2021-09-16 09:00:00, number=CHG17486, requested_by=Bobby, cmdb_ci=Reservation, start_date=2021-09-16 03:00:00}',
'{end_date=2021-09-16 12:00:00, number=CHG17441, requested_by=Ryan, cmdb_ci=Payment, start_date=2021-09-16 03:00:00}']
output = []
for data in stack:
data = data.replace("{","").replace("}","").split(",")
format_dict = {}
for record in data:
key, value = record.split("=")
format_dict[key.strip()] = value.strip()
output.append(format_dict)
print(output)