5

I have a YAML file whose contents look like:

a: 45
b: cheese
c: 7.8

I want to be able to read this information into variables in python but after extensive googling I can't work out if this is possible or do I have to put it into another python type first before it can be put into variables? Ultimately I want to use the values from a and c for calculations.

1

3 Answers 3

5

Generally, there's nothing wrong with using a dictionary as would result from using yaml.load("""a: 45\nb: cheese\nc: 7.8""") -- if you really must get these into the namespace as actual variables, you could do:

>>> y = yaml.load("""a: 45
... b: cheese
... c: 7.8""")
>>> globals().update(y)
>>> b
"cheese"

but I don't recommend it.

Sign up to request clarification or add additional context in comments.

3 Comments

why would you not recommend it
@user_h For one thing, the yaml package doesn't ship with Python.
Old thread, but the big reason not to do it is that modifying your globals can overwrite important names. globals().update(yaml.load("str: 42\nsuper: hi hello")) will do bad things to the rest of your code; allowing user-defined strings and things into your environment is also a major security concern. So just avoid it ;) @user_h
4

The issue is in the way your information is being stored. See the YAML specification. The information you supplied will return as a string. Try using an a parser like this parser on your information to verify it returns what you want it to return.

That being said. To return it as a dictionary it has to be saved as

 a: 45 
 b: cheese
 c: 7.8

Above is the correct format to save in, if you would like to represent it as a dictionary.

below is some python code on that. please note i save the information to a file called information.yaml

 import yaml
 with open('information.yaml') as info:
      info_dict = yaml.load(info)

1 Comment

Libraries should never be installed outside a virtualenv, note
0

First, you need a space after the colon to make it a legit yaml(wiki:searchcolon). For more information about pyyaml, click here.

#pip install pyyaml

In [1]: text="""
   ...: a: 45
   ...: b: cheese
   ...: c: 7.8"""

In [2]: import yaml

In [3]: print yaml.load(text)
{'a': 45, 'c': 7.8, 'b': 'cheese'}

And now you are good to go :)

In case someone is interested in why space matters:

In [4]: text1="""
a:45
b:cheese
c:7.8"""

In [6]: print yaml.load(text1)
a:45 b:cheese c:7.8

1 Comment

Libraries should never be installed outside a virtualenv, note.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.