I'd like to be able to take the YAML defined below and turn it into a dictionary.
development:
user:dev_uid
pass:dev_pwd
host:127.0.0.1
database:dev_db
production:
user:uid
pass:pwd
host:127.0.0.2
database:db
I have been able to use the YAML library to load the data in. However, my dictionary appears to contain the environmental items as a long string.
This code:
#!/usr/bin/python3
import yaml
config = yaml.load(open('database.conf', 'r'))
print(config['development'])
yields the following output.
user:dev_uid pass:dev_pwd host:127.0.0.1 database:dev_db
I can't access any of the entries by key name or load that string subsequent using the yaml.load
method.
print(config['development']['user'])
This code yields the following error:
TypeError: string indices must be integers
Ideally I would like to end up with a parsing function that returns a dictionary or a list
so I can access the properties by key name or using the dot
operator like:
print(config['development']['user'])
config.user
Where am I going wrong?
Your "yaml" is not a mapping of mappings, it's a mapping of strings. In YAML 1.2, block mapping entries need whitespace after the separator, e.g.
development:
user: dev_uid
pass: dev_pwd
host: 127.0.0.1
database: dev_db
production:
user: uid
pass: pwd
host: 127.0.0.2
database: db
Don't try to pre-process this text. Instead, find who generated the markup and throw the spec at them.
Since you are not getting what you want with the yaml
module immediately, your .conf file is probably using a format different than what the yaml
module currently expects.
This code is a quick workaround that gives you the dictionary you want:
for mainkey in ['production','development']:
d = {}
for item in config[mainkey].split():
key,value = item.split(':')
d[key] = value
config[mainkey] = d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With