psniffer
psniffer

Reputation: 113

iterate list adding to dictionary

objective

loop round a list, if the list does not start with whitespace then use this as a dictionary key, if it does start with whitespace use this as a dictionary value

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)

The above does not work ...

print dic
{'': [], 'Three': [' Two'], 'One': []}

what is the best way to achieve this?

Upvotes: 0

Views: 5229

Answers (1)

K.Suthagar
K.Suthagar

Reputation: 2306

Use this following code,

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)

Output is like this : {'One': [' Two'], 'Three': [' Four']}

No use of List lis here

Upvotes: 1

Related Questions