循环遍历列表,如果列表不以空格开头,则将其用作字典键,如果它以空格开头,则将其用作字典值
output = '''One
Two
Three
Four'''
splitLines = output.splitlines()
dic = {}
lis = []
for i in splitLines:
if not i.startswith(" "):
dic[i] = lis
lis = []
if i.startswith(" "):
lis.append(i)
以上不起作用......
print dic
{'': [], 'Three': [' Two'], 'One': []}
实现这一目标的最佳方法是什么?
答案 0 :(得分:1)
使用以下代码
output = '''One
Two
Three
Four'''
splitLines = output.splitlines()
dic = {}
dicKey=''
for i in splitLines:
if not i[0]==(" "):
dicKey=i
dic[i] = []
else:
dic[dicKey].append(i)
print(dic)
输出如下:{'One': [' Two'], 'Three': [' Four']}
此处不使用列表lis