How to transverse yaml file using variable in a function?

Viewed 92

I am completely new to python and trying to write a script for work. Here is a sample snippet:

config.yml:

company1:
    threshold: 3
    alert:
        alert1: 0
        alert2: 0
company2:
    threshold: 6
    alert:
        alert1: 1
        alert2: 1

My Python script:

import yaml
from box import Box

with open("config.yml", 'r') as open_file:
    try:
        cfg = Box(yaml.safe_load(open_file))
    except yaml.YAMLError as err:
        print(err)

def myDef(foo):
    t = cfg.foo.threshold
    a1 = cfg.foo.alert.alert1
    
    return t, a1
    
v = myDef("company1")
print(v[0])
#desired result: 3

x = myDef("company2")
print(x[1])
#desired result: 1

Currently, I get an error: BoxKeyError: "'Box' object has no attribute 'foo'"

Any help is much appreciated.

1 Answers
    t = cfg.foo.threshold

This is not referring to the local variable foo. It's trying to get the literal "foo" value from your dictionary. You probably want

    t = cfg[foo].threshold

I might also recommend not using the Box library at first. It looks like it does some fun interpreter magic to make your dictionaries more Javascript-like, and if you're just learning Python you're going to get confused and run into more situations like this where the Box solution is not the Pythonic one, and you'll be learning incorrect idioms.

Related