Python列表拆分为一个dict
有以下格式的python列表Python列表拆分为一个dict,python,list,python-2.7,dictionary,Python,List,Python 2.7,Dictionary,有以下格式的python列表 mylist = [u'Name:', u'John', , u'Doe', u'Address:', u'Washington Street ', u'Chicago'] 键的右端有:',在本例中是名称和地址。 新的格言应该是这样的: newdict = { 'Name': '["John", "Doe"]', 'Address': '["Washington Street", "Chicago"]', } 虽然使用起来不一定直观,但您可以利用它的工作原理
mylist = [u'Name:', u'John', , u'Doe', u'Address:', u'Washington Street ', u'Chicago']
键的右端有:'
,在本例中是名称
和地址
。
新的格言应该是这样的:
newdict = {
'Name': '["John", "Doe"]',
'Address': '["Washington Street", "Chicago"]',
}
虽然使用起来不一定直观,但您可以利用它的工作原理:
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']}