gpt4 book ai didi

python - 如何在函数中使用变量来遍历yaml文件?

转载 作者:行者123 更新时间:2023-12-04 14:59:26 24 4
gpt4 key购买 nike

我是 python 的新手,正在尝试编写工作脚本。这是一个示例片段:

配置文件:

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

我的 Python 脚本:

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

目前,我得到一个错误:BoxKeyError:“'Box' 对象没有属性 'foo'”

非常感谢任何帮助。

最佳答案

    t = cfg.foo.threshold

这不是指局部变量 foo。它试图从您的字典中获取文字 "foo" 值。你可能想要

    t = cfg[foo].threshold

我可能还建议一开始不要使用 Box 库。看起来它做了一些有趣的解释器魔术,使你的字典更像 Javascript,如果你只是学习 Python,你会感到困惑并遇到更多这样的情况,其中 Box 解决方案不是 Pythonic 解决方案,你会学到不正确的习语。

关于python - 如何在函数中使用变量来遍历yaml文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67248843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com