Reputation: 1481
I am trying to load a configuration file into a dictionary with just one liner
The configuration file looks like this:
key1:
nested-key1 = val1
nested-key2 = val2
key2:
nested-key3 = val3
The dictionary I'm trying to build should look like this:
{ key1:{nested-key1:val1, nested-key2:val2}, key2:{nested-key3:val3}}
By one liner I mean that I don't want to use a loop - just a fixed sequence of function calls (Number of key may vary).
something like:
f = open("/tmp/config")
dic = f.read().split("\n\n") ...
Upvotes: 2
Views: 115
Reputation: 32522
Considering the similarity of the file format to the YAML format, I suggest you use a YAML parser:
import yaml
s = """
key1:
nested-key1 = val1
nested-key2 = val2
key2:
nested-key3 = val3
"""
print yaml.load(s.replace("=", ":"))
The output is:
{'key2': 'nested-key3 , val3', 'key1': 'nested-key1 , val1 nested-key2 , val2'}
For reference:
Upvotes: 3