Python List拆分成dict

时间:2014-05-10 18:33:42

标签: python list python-2.7 dictionary

有以下格式的python列表

mylist = [u'Name:', u'John', , u'Doe', u'Address:', u'Washington Street ',  u'Chicago']

密钥末尾有':',在这种情况下是NameAddress。 新的词典应该是这样的:

newdict = {
'Name': '["John", "Doe"]', 
'Address': '["Washington Street", "Chicago"]',
}

1 个答案:

答案 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']}