我有以下 Python 2.6 程序和 YAML 定义(使用PyYAML):
import yaml
x = yaml.load(
"""
product:
name : 'Product X'
sku : 123
features :
- size : '10x30cm'
weight : '10kg'
"""
)
print type(x)
print x
这导致以下输出:
<type 'dict'>
{'product': {'sku': 123, 'name': 'Product X', 'features': [{'weight': '10kg', 'size': '10x30cm'}]}}
x
可以使用来自?的字段创建对象
我想要以下内容:
print x.features[0].size
我知道可以从现有类创建和实例化,但这不是我想要的这个特定场景。
编辑:
- 更新了关于“强类型对象”的令人困惑的部分。
features
按照 Alex Martelli 的建议更改了对索引器的访问