迭代列表添加到字典

时间:2016-12-29 12:12:42

标签: python loops dictionary

目标

循环遍历列表,如果列表不以空格开头,则将其用作字典键,如果它以空格开头,则将其用作字典值

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': []}

实现这一目标的最佳方法是什么?

1 个答案:

答案 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