I have a list with categories followed by some elements. Given that I know all the category names, is there a way to turn this into a dictionary of lists, i.e. convert:
l1 = ['cat1', 'a', 'b', 'c', 'cat2', 1,2,3, 'cat3',4,5,6,7,8]
into:
l1_dic = {'cat1': ['a', 'b', 'c'], 'cat2': [1, 2, 3], 'cat3': [4, 5, 6, 7, 8]}
Edit: It is possible that the categories do NOT have a common string e.g. ‘cat1’ could be replaced by ‘Name’ while ‘cat2’ could be ‘Address’.
Like I said, in my original post, we do know the category names i.e. we do potentially have a list l2 such that:
l2 = ['cat1', 'cat2', 'cat3']
Once again, the category names need not necessarily have a common string.
>Solution :
As you know the categories, a simple loop with tracking of the last key should work:
categories = {'cat1', 'cat2', 'cat3'}
out = {}
key = None
for item in l1:
if item in categories:
out[item] = []
key = item
else:
out[key].append(item)
output:
{'cat1': ['a', 'b', 'c'],
'cat2': [1, 2, 3],
'cat3': [4, 5, 6, 7, 8]}