pythondictionary-comprehension

Splitting a text string into a list of dictionaries


I start out with this little ditty, but would need to clean it up, create key-value pairs and for each customer, create their own dictionary part of a list of customer dictonaries.

service_notes = ['Customer AliceJenkins\n',
 'Car Honda\n',
 'Service Fifty_Thousand\n','Customer BobElliot\n',
 'Car Toyota, Rav4, Silver, 2018\n',
 'Service Thirty_Thousand,\n',
 'Customer CharlieWallace\n',
 'Car Ford\n',
 'Service Ten_Thousand\n']

Firstly, I cleaned up the listed string with overthinking by creating a delimited between would-be key-value pairs, but ran into difficulty in the Car Toyota section) and finally removed the line change.

then when I tried to split the values into key-value pairs, i got an error for using str split functions on a list. so made the list into a str... and well yeah. didnt work.


data_arr = [entry.replace(" ", ": ").replace(",:", " ").replace("\n","") for entry in service_notes]
data_arr = str(data_arr)
sep = ': '
lst = data_arr.split(sep)
d = dict(zip(lst[0::2], lst[1::2]))
print(d)

end results is not a useable dictionary. nor could i create dictionaries for each customer entry.

{"['Customer": "AliceJenkins', 'Car", "Honda', 'Service": "Fifty_Thousand', 'Customer", "BobElliot', 'Car": "Totota  Rav4  Silver  2018', 'Service", "Thirty_Thousand,', 'Customer": "CharlieWallace', 'Car", "Ford', 'Service": "Ten_Thousand']"}

Solution

  • Here you go:

    # Remove the commas & trailing space(s), then split on the first space for each item
    data_arr = [entry.replace(",","").strip().split(" ",1) for entry in service_notes]
    
    # Create a list of dictionaries, each made from 3 consecutive elements of data_arr
    dict_arr = [dict(datum) for datum in zip(data_arr[0::3], data_arr[1::3], data_arr[2::3])]