I am working on a script to read through a YAML config and am having some problems with the logic with the for loops and dictionary. I can get it to print each value when done static, but this throws off the purpose of my script. As I would like to dynamically call functions using the YAML config file.
So far I can only get the first key and value from my for script. Anytime I try to go further by using dataMap[key][0][value] I cannot go further then 1.
import yaml
with open('design.yaml') as f:
dataMap = yaml.safe_load(f)
print("================================")
print("Topo #1")
print("================================")
print(f"Topo Name: {dataMap['topology'][0]['name']}")
print(f"vPort: {dataMap['topology'][0]['vport']}")
print(f"DG Name: {dataMap['topology'][1]['devicegroup']}")
print(f"Multiplier: {dataMap['topology'][1]['multiplier']}")
print(f"Eth Name: {dataMap['topology'][1]['eth']['name']}")
print("Auto Output - To look just like above")
print("================================")
for key, value in dataMap.items():
#Updated
print("KEY: {} - VALUE: {}".format(key, value[0].items()))
print("====")
print("================================")
#print("Recursive Function Test")
#print("================================")
#myprint(dataMap)
config:
-name: Test
topology:
- name: DC1
vport: Port1
- devicegroup: DC1 DG1
multiplier: 50
eth:
name: ETH1
macStart: 00:01:01:01:00:01
macStep: 00:00:00:00:00:01
enableVLAN: True
vlanID: 100
vlanStep: 0
ipv4:
name: DC1 DG1 IPv4
startIP: 10.1.1.10
stepIP: 0.0.0.1
netmask: 255.255.255.0
gateway: 10.1.1.1
gwStep: 0.0.0.0
- name: TEST2
vport: Port2
- devicegroup: TEST DG2
Output:
KEY: config - VALUE: dict_items([('apiServer', '10.255.251.105'), ('apiServerPort', 443), ('osPlatform', 'linux'), ('username', 'admin'), ('password', 'admin'), ('chassisIP', '10.253.0.82'), ('licenseserver', '10.253.0.82'), ('licensemode', 'subscription'), ('licensetier', 'tier3'), ('POCName', 'XXXXX'), ('POCNumber', 'XXXXX')])
====
KEY: topology - VALUE: dict_items([('name', 'DC1'), ('vport', 'Port1')])
My problem is now, how do I pull in the devicegroup information from the YAML file? Changing value[0] to value[1] causes an index issue.
print("KEY: {} - VALUE: {}".format(key, value[1].items()))
IndexError: list index out of range
So how do I step further into the YAML file with this?
I am not 100% sure, but I don't think a function call within an f-string is evaluated, so try and do:
print("KEY: {} - VALUE: {}".format(key, value[0].items()))
instead.
Additionally the value for the key
config is a sequence (i.e. loaded as a Python list) that has only one element, so you cannot index further in that sequence then 0
.
You'd better try and do something like:
for key, values in dataMap.items():
for idx, value in enumerate(values):
print("KEY: {} - VALUE[{}]: {}".format(key, idx, value.items()))
print("====")