1
votes

My situation is following. I have a sting "list" like this

Text1
Text2: value1
Text3:
Text4:
Text5: value2
...

Now I want to split the text into a dictionary with Key-Value Pair.

I tryed it with this 1liner

sp = dict(s.split(':') for s in list.split('\n') if len(s) > 1 and s.count(':') > 0)

This works great until there is no value like in Text3 and Text4.

My final dictionary should look like this

{ Text2:value1,Text3:'',Text4:'',Text5:value2 }

Text1 should be skipped - but Text3 & Text4 I need in the dictionary, also if the value is empty.

2
I'm getting the expected output which you have mentioned. It has skipped Text1PySaad
yes, i too am getting your expected output.Suraj Subramanian
Your code works in python2.7 and 3.5. Do not use list keyword for a variable. Instead of doing s.count(':') > 0, you can just do ':' in sTeshan Shanuka J
ValueError: dictionary update sequence element #75 has length 3; 2 is required - I use python 3.6user3352603
I found the issue causing this problem - I have one Element with Key:http:// xyz .com This would get split in 3 parts - so how can I skip such lines with more than 2 Elements ??user3352603

2 Answers

1
votes

for your case Key:http:// xyz .com you have to stop the split after the first match using s.split(':', 1)):

my_str = """Text1
Text2: value1
Text3:
Text4:
Text5: value2
Key:http:// xyz .com 
"""

sp = dict(map(str.strip, s.split(':', 1)) for s in my_str.split('\n') if ':' in s)
print(sp)

output:

{'Text2': 'value1', 'Text3': '', 'Text4': '', 'Text5': 'value2', 'Key': 'http:// xyz .com'}
1
votes

Because of this issue, which I only found with the help of comments, I could solve the problem this way

my_str = """Text1
Text2: value1
Text3:
Text4:
Text5: value2
Text6:http: // something
"""

The problem was, that the last row was split in 3 parts because of the webadress in the value field.

sp = dict(s.split(':') for s in my_str.split('\n') if len(s) > 1 and s.count(':') == 1)

Maybe there is a nicer way, but I checked if the split char ":" only accours 1 time - because then I am sure to get a pair, I can insert into the dictionary :)