有以下格式的python列表
mylist = [u'Name:', u'John', , u'Doe', u'Address:', u'Washington Street ', u'Chicago']
密钥末尾有':'
,在这种情况下是Name
和Address
。
新的词典应该是这样的:
newdict = {
'Name': '["John", "Doe"]',
'Address': '["Washington Street", "Chicago"]',
}
答案 0 :(得分:0)
虽然不一定直观地使用itertools.groupby,但您可以利用它的工作原理:
res = {}
for iskey, it in groupby(mylist, lambda s: s.endswith(':')):
if iskey:
for k in it:
key = k[:-1]
res[key] = []
else:
res[key].extend(it)
res
=> {u'Address': [u'Washington Street ', u'Chicago'], u'Name': [u'John', u'Doe']}