I have a list that looks something like this:
list1 = ['390140', 'string3', 'string2', '631019', 'string1', '', '6059152', 'string4', 'string5', '', '6951201', 'string6']
I have to convert this list into a list of dictionaries as below:
list2 = [{'code':'390140','description': 'string3 string2'}, {'code':'631019','description':'string1 '},{'code':'6051952','description': 'string4 string5', ...]
whereas each digit is a code and the following strings are the description. I have tried to the index of the digits and then slice the main list into sub-lists as shown in my approach below. This approach is not working.
#x = [item for item in list1 if item.isdigit()]
idx = [idx for idx, item in enumerate(list1) if item.isdigit()]
for i in idx:
list2.append({'code': list1[i], 'description': ' '.join(list1[idx[i]:idx[i+1]])})
list2 is the output I wish to obtain.
Shortly with itertools.groupby function:
from itertools import groupby
list1 = ['390140', 'string3', 'string2', '631019', 'string1', '', '6059152', 'string4', 'string5', '', '6951201', 'string6']
groups = groupby(list1, key=str.isdigit)
codes = [{'code': next(g), 'description': ' '.join(next(groups)[1])} for _, g in groups]
print(codes)
The output:
[{'code': '390140', 'description': 'string3 string2'},
{'code': '631019', 'description': 'string1 '},
{'code': '6059152', 'description': 'string4 string5 '},
{'code': '6951201', 'description': 'string6'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With