Parsing yaml file and getting a dictionary

11,466

Solution 1

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.

Solution 2

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
Share:
11,466
Shawn Taylor
Author by

Shawn Taylor

Updated on June 08, 2022

Comments

  • Shawn Taylor
    Shawn Taylor almost 2 years

    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?

  • Shawn Taylor
    Shawn Taylor almost 6 years
    That would be me. :( Thanks for your help!
  • Dave R
    Dave R almost 5 years
    I've been flumoxxed by this since last week - this is the first YAML item I've seen that mentions anything about the importance of whitespace! I had no clue from others I've read......