Python: How to split string containing extra delimeters as value

Viewed 33

I am using python and reading "attribute.txt" file

Contents of attribute.txt file is in "Key: value" format, as shown below:

For e.g.

data: Test data
version: 3.1
system: windows

My Python code to read and split contents line by line looks like this.

 with open(self.attrib_file) as f:
            self.txtdict = dict(l.strip().split(':') for l in f)

Above code is working fine, but failing for data that have colon ":" character in value part of it.

For eg.

data: Test data
version: 3.1
system: windows: unix   <-- This line will fail as it have two colons. 

How can i make sure that "key" system have value "windows: unix" ?

1 Answers

If the keys do not have semicolons:

print(dict(l.strip().split(':', 1) for l in f))

Output

{'data': ' Test data', 'version': ' 3.1', 'system': ' windows: unix'}
Related