可以使用下面的示例代码来定义嵌套字典和嵌套列表的yaml文件:

# 嵌套字典
person:
  name: Alice
  age: 30
  address:
    city: Shanghai
    country: China

# 嵌套列表
fruits:
  - Apple
  - Banana
  - Orange

在上面的示例中,person是一个嵌套字典,它包含三个键值对:nameageaddress。其中address又是一个嵌套字典,它包含两个键值对:citycountry

fruits是一个嵌套列表,它包含三个元素:AppleBananaOrange

要使用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字典。你可以像操作普通字典一样操作它,例如访问personaddress

print(data['person']['address'])
# 输出:{'city': 'Shanghai', 'country': 'China'}
``
python yaml文件定义嵌套字典嵌套列表

原文地址: https://www.cveoy.top/t/topic/ervG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录