Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list:
data = ['**adjective:**', 'nice', 'kind', 'fine',
'**noun:**', 'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal',
'**adverb:**', 'well', 'nicely', 'fine', 'right', 'okay']
I would be able to get:
[{'**adjective**': ('nice', 'kind', 'fine'),
'**noun**': ('benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal'),
'**adverb**': ('well', 'nicely', 'fine', 'right', 'okay')}]
解决方案
This might be as close at it gets to what you have asked:
d = collections.defaultdict(list)
for s in data:
if s.endswith(":"):
key = s[:-1]
else:
d[key].append(s)
print d
# defaultdict(,
# {'adjective': ['nice', 'kind', 'fine'],
# 'noun': ['benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal'],
# 'adverb': ['well', 'nicely', 'fine', 'right', 'okay']})
Edit: Just for fun an alternative two-liner inspired by the answer by SilentGhost:
g = (list(v) for k, v in itertools.groupby(data, lambda x: x.endswith(':')))
d = dict((k[-1].rstrip(":"), v) for k, v in itertools.izip(g, g))