我正在使用Python开发一个软件,我需要读取一个有多个层次的YAML文件,如下所示。
#Filename: SampleCase.yml
%YAML 1.1
VesselTypes:
- Name: Escort Tug
Length: 32
Breadth: 12.8
Depth: 9
Draughts:
- Name: Draught1
Mass: 500
CentreOfGravity: [16.497, 0, 4.32]
TowingStaples:
- Name: Staple1
Position: [0, 0, 0]
Thrusters:
- Name: Port Propeller
Position: [0, -1, 0]
MaxRPM: 1800
MaxPower: 2525
- Name: Stbd Propeller
Position: [0, 1, 0]
MaxRPM: 1800
MaxPower: 2525
- Name: Ship
Vessels:
- Name: Tug
VesselType: Escort Tug
Draught: Draught1
InitialPosition: [0, 0, 0]
Orientation: [0, 0, 0]
- Name: Tanker
VesselType: Ship
Draught: Draught1
InitialPosition: [0, 0, 0]
Orientation: [0, 0, 0]
Speed: 8
在这里,有两艘名为 "拖船 "和 "油轮 "的船只。它们属于两种船舶类型,"护航拖船 "和 "船舶"。
#Filename: main.py
import yaml
# Reading YAML data
file_name = 'SampleCase.yml'
with open(file_name, 'r') as f:
data = yaml.load(f)
print(data["Vessels"][0]["Name"])
我能够使用索引号(例如:data["Vessels"][0]["Name"]
)访问存储的数据,但是我想使用匹配的键来访问它们。例如,我想打印名为 "Tug "的船只的港口螺旋桨的MaxRPM值。在python中这样做的标准方法是什么?