4

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.

user_h
  • 135
  • 1
  • 3
  • 11

3 Answers3

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.

a p
  • 3,098
  • 2
  • 24
  • 46
  • why would you not recommend it – user_h Oct 07 '15 at 23:26
  • @user_h For one thing, the yaml package doesn't ship with Python. – personal_cloud Sep 17 '17 at 02:43
  • 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 – a p Sep 17 '17 at 04:56
3

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)
tockards
  • 189
  • 6
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
B.Mr.W.
  • 18,910
  • 35
  • 114
  • 178