1

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.

5
  • 3
    I'm getting the expected output which you have mentioned. It has skipped Text1 Commented Mar 28, 2020 at 9:58
  • 1
    yes, i too am getting your expected output. Commented Mar 28, 2020 at 9:58
  • 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 s Commented Mar 28, 2020 at 10:32
  • ValueError: dictionary update sequence element #75 has length 3; 2 is required - I use python 3.6 Commented Mar 28, 2020 at 10:33
  • 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 ?? Commented Mar 28, 2020 at 11:29

2 Answers 2

1

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'}
Sign up to request clarification or add additional context in comments.

1 Comment

you edited the message, while I was writing the answer I found - thanks for your support !
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.