Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing yaml file and getting a dictionary

Tags:

python

pyyaml

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?

like image 951
Shawn Taylor Avatar asked May 22 '18 16:05

Shawn Taylor


2 Answers

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.

like image 131
wim Avatar answered Sep 21 '22 00:09

wim


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
like image 41
vasia Avatar answered Sep 20 '22 00:09

vasia