12.yaml的简单使用

YAML讲义

字典

{"age" : "18", "name" : "liqing"}
age: "18"

列表

[1, 2, xiaoming]
- "1"
- "2"
- "xiaoming"

字典和列表的嵌套

  • 字典与字典的嵌套
{person1:{age:18, name : xiaoming}, person2:{age:19, name : xiaohong} , num: 20}
person1:
  age: "18"
  name: "xiaoming"
person2:
  age: "19"
  name: "xiaohong"
num: "20"
  • 字典嵌套列表
{person1: xiaoming, person2: [1, 2, 3]}
person1: "xiaoming"
person2: 
  - "1"
  - "2"
  - "3"
  • 列表嵌套字典
[{person1:18}, 2, 3, {person2:20}]
- 
  person1: "18"
- "2"
- "3"
- 
  person2: "20"
  • 列表嵌套列表
[1, 2, [3, 4, 5], 6]
- "1"
- "2"
- 
  - "3"
  - "4"
  - "5"
- "6"
  • yaml 的读
import yaml
with open("./data.yaml") as f:
  yaml.load(f)
  • yaml 的写
import yaml
aproject = {'name': 'Silenthand Olleander',
            'race': 'Human',
            'traits': ['ONE_HAND', 'ONE_EYE']
            }

print(yaml.dump(aproject,))
  • 练习1
{key1 : {age: 18, name: xiaoming, person: [1, 2, 3, {person2: 4, person3: 5}], height: 100}, key2:[7, 8, 9]}
key1: 
  age: "18"
  name: "xiaoming"
  person:
    - "1"
    - "2"
    - "3"
    - 
       person2: "4"
       person3: "5"
  height: "100"
key2:
  - "7"
  - "8"
  - "9"
  • 练习2
[1, 2, 3, [4,5,6], {person:[1, 2, 3,]}, 5, {age:18,name:xiaoming}, [7,{age:18,name: xiaohong}] ]
- "1"
- "2"
- "3"
- 
  - "4"
  - "5"
  - "6"
- 
  person: 
    - "1"
    - "2"
    - "3"
- "5"
- 
  age: "18"
  name: "xiaoming"
- 
  - "7"
  - 
     age: "18"
     name: "xiaohong"
  • 纯量
str1: "1"
str2: "x"
int1: 1
int2: 20
decimal1: 3.14
float1: 3.1415926535897932384626433
boolean1: True
boolean2: False
boolean3: true
boolean4: TRUE
null1: null
null2: Null
null3: NULL
time1: 2018-01-01 10:38:20.2060
  • 布尔类型仅支持全大写,全小写,首字母大写
  • 空值使用null来表示
  • yaml 中不是字符串的包括:整数, float, bool, none, time
  • 锚点和引用
data: &info
  value: "456"
name:
  value1: "123"
  <<: *info
  • 常见错误
    • yaml 中包含中文
    • yaml 中空格位数不对
    • yaml 中的数据是直接复制的,使用了 tab 键,pycharm 不能转换
    • yaml 不能表示元组(yaml 是各种语言通用的)

转载于:https://www.cnblogs.com/liqing45/p/9504145.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值