Reputation: 119
I have a yaml file with the below structure:
this is test.yaml
server:
- host: ubuntu
ip: 10.20.30.40
path: /var/log/syslog
- host: ubuntu
ip: 10.20.3.50
path: /var/log/syslog
When I call in my python script,I load the yaml file and parse the contents. I cannot iterate all the contents though:
How can I create a list in the below format:
import yaml
def read_yaml(file):
with open(file, "r") as stream:
try:
config = yaml.load(stream)
print("inside the function")
# print(config)
except yaml.YAMLError as exc:
print(exc)
print("\n")
return config
d = read_yaml("config.yaml")
print('{host}@{ip}:{path}'.format(*d['server']))
I want an output with host@ip:path for the different servers in the yaml file. But the command above does not work and generates an error: TypeError: format() argument after ** must be a mapping, not list or KeyError:Host
please help.
Upvotes: 0
Views: 321
Reputation: 5469
You unpack a list (d['server']
) as an argument to format
. But format wants named keyword arguments (kwargs) in this case.
Since you should only hope to print 1 item in each such print
call you have, try:
for item in d['server']:
print('{host}@{ip}:{path}'.format(**item))
Upvotes: 2