Load data from a YAML file into variables in python

17,369

Solution 1

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.

Solution 2

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)
Share:
17,369
user_h
Author by

user_h

Updated on June 04, 2022

Comments

  • user_h
    user_h almost 2 years

    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.