Python YAML 文件定义嵌套字典和列表
可以使用下面的示例代码来定义嵌套字典和嵌套列表的 YAML 文件:
# 嵌套字典
person:
name: 'Alice'
age: 30
address:
city: 'Shanghai'
country: 'China'
# 嵌套列表
fruits:
- 'Apple'
- 'Banana'
- 'Orange'
在上面的示例中,'person' 是一个嵌套字典,它包含三个键值对:'name'、'age' 和 'address'。其中 'address' 又是一个嵌套字典,它包含两个键值对:'city' 和 'country'。
'fruits' 是一个嵌套列表,它包含三个元素:'Apple'、'Banana' 和 'Orange'。
要使用 Python 读取上面的 YAML 文件,可以使用 PyYAML 库。下面是一个示例代码:
import yaml
with open('example.yaml', 'r') as f:
data = yaml.load(f, Loader=yaml.FullLoader)
print(data)
运行上面的代码,输出结果如下:
{'person': {'name': 'Alice', 'age': 30, 'address': {'city': 'Shanghai', 'country': 'China'}}, 'fruits': ['Apple', 'Banana', 'Orange']}
可以看到,PyYAML 库成功将 YAML 文件加载为 Python 字典。你可以像操作普通字典一样操作它,例如访问 'person' 的 'address':
print(data['person']['address'])
# 输出:{'city': 'Shanghai', 'country': 'China'}
原文地址: https://www.cveoy.top/t/topic/nRSs 著作权归作者所有。请勿转载和采集!