Parsing yaml python
Question: There is a file in yaml markup

    
    
     a:
      b:x
      test2
      test
      test3
    

How to use python (2.7.x) and PyYAML get x?


Answer: You can't! The YAML you posted results in a dict containing just a single key,
`a` which maps to the value `"b:x test2 test test3"` \- you can easily test
that by [pasting your YAML here](http://yaml-online-parser.appspot.com/).

The reason for this is that you cannot mix `key: value` pairs and keyless
items (like there would be in an array).

However, let's assume that you have proper YAML that contains an object `a`
containing another object that maps `b` to `x`. For example this:

    
    
    a:
        b: x
        c: test2
        d: test
        e: test3
    

In this case you'd use `foo['a']['b']` to access `x` with `foo` being the
object returned by your YAML parser.

The python code to get `foo` could look like this:

    
    
    import yaml
    with open('yourfile.yaml') as f:
        foo = yaml.safe_load(f)
    

I'm using `safe_load` since you most likely do not intend to create arbitrary
Python objects from your YAML document and thus you want to use a function
that cannot open a security hole if ever passed a malicious YAML document.

