将 YAML 加载为嵌套对象而不是 Python 中的字典 [英] Load YAML as nested objects instead of dictionary in Python
问题描述
我在 YAML 中有一个配置文件,当前使用 yaml.safe_load 作为字典加载.为了方便编写我的代码,我更愿意将它作为一组嵌套对象加载.引用字典的更深层次很麻烦,使代码更难阅读.
示例:
导入yamlmydict = yaml.safe_load("""一:1乙:- q: "foo"回复: 99秒:98- x:酒吧"y: 97z: 96C:d:7电子:8f: [9,10,11]""")
目前,我访问诸如
之类的项目mydict["b"][0]["r"]>>>99
我希望能够访问相同的信息,例如
mydict.b[0].r>>>99
有没有办法像这样将 YAML 加载为嵌套对象?或者我是否必须滚动自己的类并递归地将这些字典翻转为嵌套对象?我猜namedtuple可以让这更容易一些,但我更喜欢整个事情的现成解决方案.
找到了一个方便的库来满足我的需求:https://github.com/Infinidat/munch
导入yaml从蒙克进口蒙克mydict = yaml.safe_load("""一:1乙:- q: "foo"回复: 99秒:98- x:酒吧"y: 97z: 96C:d:7电子:8f: [9,10,11]""")mymunch = 蒙克(mydict)
(我必须编写一个简单的方法来递归地将所有 subdicts 转换为 munches,但现在我可以使用例如
<预><代码>>>>mymunch.b.q富"I have a configuration file in YAML that is currently loaded as a dictionary using yaml.safe_load. For convenience in writing my code, I'd prefer to load it as a set of nested objects. It's cumbersome to refer to deeper levels of the dictionary and makes the code harder to read.
Example:
import yaml
mydict = yaml.safe_load("""
a: 1
b:
- q: "foo"
r: 99
s: 98
- x: "bar"
y: 97
z: 96
c:
d: 7
e: 8
f: [9,10,11]
""")
Currently, I access items like
mydict["b"][0]["r"]
>>> 99
What I'd like to be able to do is access the same information like
mydict.b[0].r
>>> 99
Is there a way to load YAML as nested objects like this? Or will I have to roll my own class and recursively flip these dictionaries into nested objects? I'm guessing namedtuple could make this a bit easier, but I'd prefer an off-the-shelf solution for the whole thing.
Found a handy library to do exactly what I need: https://github.com/Infinidat/munch
import yaml
from munch import Munch
mydict = yaml.safe_load("""
a: 1
b:
- q: "foo"
r: 99
s: 98
- x: "bar"
y: 97
z: 96
c:
d: 7
e: 8
f: [9,10,11]
""")
mymunch = Munch(mydict)
(I had to write a simple method to recursively convert all subdicts into munches but now I can navigate my data with e.g.
>>> mymunch.b.q
"foo"
这篇关于将 YAML 加载为嵌套对象而不是 Python 中的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!