我的YAML数据如下
- gms:
- localhost1:
address: 192.168.56.101
username: root
password: xxxxxx
command: "uptime"
hostname: mydev_machine
我正在尝试使用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']
如果我查看print(data_loaded)
输出
[{'gms': [{'localhost1': {'address': '192.168.56.101', 'username': 'root', 'password': 'xxxxxx', 'command': 'uptime', 'hostname': 'mydev_machine'}}]}]
但我收到错误
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
答案 0 :(得分:2)
element.get('gms')
或element['gms']
会产生一个列表。您需要迭代列表。
for element in data_loaded:
for item in element.get('gms'):
print(item.get('localhost1').get('address'))
您还可以像这样访问list
的元素:
element['gms'][0]['localhost1']['address']