[英]Python: YAML data parsing from a file
I have YAML data as below 我有以下YAML数据
- gms:
- localhost1:
address: 192.168.56.101
username: root
password: xxxxxx
command: "uptime"
hostname: mydev_machine
and I am trying to extract values of address
, password
, command
, hostname
with below logic in python 我正在尝试使用以下逻辑在python中提取address
, password
, command
, hostname
值
import yaml
with open("host_data.yaml",'r') as stream :
data_loaded = yaml.load(stream)
for element in data_loaded:
address=element['gms']['localhost1']['address']
username=element['gms']['localhost1']['username']
password=element['gms']['localhost1']['password']
hostname=element['gms']['localhost1']['hostname']
if I look at print(data_loaded)
output 如果我看一下print(data_loaded)
输出
[{'gms': [{'localhost1': {'address': '192.168.56.101', 'username': 'root', 'password': 'xxxxxx', 'command': 'uptime', 'hostname': 'mydev_machine'}}]}]
but I am getting error as 但我得到错误
Traceback (most recent call last):
File "Python_Programs/log_finder.py", line 12, in <module>
address=element['gms']['localhost1']['address']
TypeError: list indices must be integers or slices, not str
element.get('gms')
or element['gms']
yields a list. element.get('gms')
或element['gms']
产生一个列表。 You need to iterate the list. 您需要迭代列表。
for element in data_loaded:
for item in element.get('gms'):
print(item.get('localhost1').get('address'))
You can also access the elements of the list
like this: 您还可以像这样访问list
的元素:
element['gms'][0]['localhost1']['address']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.