1

trying to get a YAML document to parse into python dictionary object that I can manipulate. I installed pip install pyyaml.

import yaml
yamlstring = "some: var \n another: 3"
type(yaml.load(yamlstring))
>> str

to my surprise it returns a string not a dictionary! what did I do wrong here?

1
  • To my surprise you get a str as output where I expect a scanner.Error. At least Python 2.7 and 3.4 give that. What system are your running, which Python version. Commented Sep 28, 2015 at 21:21

2 Answers 2

3

Too much whitespace.

>>> import yaml
>>> yamlstring = "some: var\nanother: 3"
>>> type(yaml.load(yamlstring))
dict
Sign up to request clarification or add additional context in comments.

2 Comments

how to trim yaml white space?
@user299709 If it needs trimming, then you could use str.strip() somehow — but does it really?
2

If you want to generate a data structure from a YAML string, it makes much more sense to use triple quoted strings, starting them with an escaped newline and ending them with a newline. Your example would then look like:

import yaml
yamlstring = """\
some: var
another: 3
"""
type(yaml.load(yamlstring))

That way it is far easier to spot the extra space before another as that would indent the YAML "structure".

If you want to do this nested in a function (and thus have leading whitespace) use dedent from the textwrap standard library to remove that extra leading whitespace.

2 Comments

well this is what the yaml string looks like "options: \n preferences:\n delay: 1\n use_mouse : 1\n properties: 0\n async: 0"
@user299709 that loads correctly (as a dict of 4 elements within a dict of one element). I am not sure what you want me to do with that example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.