user3352603
user3352603

Reputation: 35

Python - split string into dictionary

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.

Upvotes: 1

Views: 108

Answers (2)

user3352603
user3352603

Reputation: 35

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 :)

Upvotes: 1

kederrac
kederrac

Reputation: 17322

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'}

Upvotes: 1

Related Questions