data structures – Converting YAML file to python dict

data structures – Converting YAML file to python dict

I think your yaml file should look like (or at least something like, so its structured correctly anyway):

     Id: i-aaaaaaaa
     environment: us-east
     serverId: someServer
     awsHostname: ip-someip
     roles: [webserver,php]

Then, yaml.load(...) returns:

{instance: {environment: us-east, roles: [webserver, php], awsHostname: ip-someip, serverName:, ipAddr:, serverId: someServer, Id: i-aaaaaaaa}}

And you can go from there…

So used like:

>>> for key, value in yaml.load(open(test.txt))[instance].iteritems():
    print key, value

environment us-east
roles [webserver, php]
awsHostname ip-someip
serverId someServer
Id i-aaaaaaaa

An additional bug in your code, that doesnt have to do with YAML:

for key in dict:
    if key in dict == instanceId: # This doesnt do what you want
        print key, dict[key]

in is an operator that works on sequence types, and also on maps. This is why this isnt a syntax error… but it doesnt do what you want.

key in dict will always evaluate to True, because all the keys youre iterating through are in the dict. So your code boils down to True == instanceId, which will always evaluate to False, because the boolean value True is never equal to that string.

You might have noticed that the print statement doesnt produce any output; this is because it never gets called.

data structures – Converting YAML file to python dict

Just use python-benedict, its a dict subclass that provides I/O support for most common formats, including yaml.

from benedict import benedict

# path can be a yaml string, a filepath or a remote url
path = path/to/data.yml

d = benedict.from_yaml(path)

# do stuff with your dict
# ...

# write it back to disk

Its well tested and documented, check the README to see all the features:

Install using pip: pip install python-benedict

Note: I am the author of this project

Leave a Reply

Your email address will not be published. Required fields are marked *