Reputation:
I would like to print from the following yaml file just the value of a
1w:
team1:
contact: [email protected]
2w:
team2:
contact: [email protected]
So far I have the following working:
#!/usr/bin/env python
import yaml
def yaml_loader(filepath):
with open(filepath, 'r') as file_descriptor:
#add condition to validate yaml
data = yaml.load(file_descriptor)
return data
def yaml_dump(filepath, data):
with open(filepath, w) as file_descriptor:
yaml.dump(data, file_descriptor)
if __name__ == "__main__":
filepath = "log/log_registration.yaml"
data = yaml_loader(filepath)
items = data.get('3w')
for item_roletype, value in items.iteritems():
print value
Just edited my post because I realized that my yaml should have a different layout to avoid multiple entries overwrites.
At this point I am not sure how to print just the name of "team1" and "team2" and others that will follow. without the contact information.
The code above will not work at this moment ...
Upvotes: 1
Views: 8642
Reputation: 551
if __name__ == "__main__":
filepath = "log/log_registration.yaml"
data = yaml_loader(filepath)
for _, value in data.iteritems():
for key, _ in value.iteritems():
print(key)
Upvotes: 0
Reputation: 12156
New yaml data
1w:
team1:
contact: [email protected]
2w:
team2:
contact: [email protected]
ok so with data = yaml_loader(filepath)
we can look at data
:
{'1w': {'team1': {'contact': '[email protected]'}},
'2w': {'team2': {'contact': '[email protected]'}}}
and we can extract the data like this
for week, teams in data.items():
for team in teams.keys():
print('{}: {}'.format(key, team))
outputs:
1w: team1
2w: team2
Original answer: I think you've somewhat over complicated things
data:
1w:
a: team1
b: [email protected]
2w:
a: team2
b: [email protected]
code:
data = yaml_loader(filepath)
for key, value in data.items():
print('{}[a] = {}'.format(key, value['a']))
outputs (with your data)
1w[a] = team1
2w[a] = team2
Upvotes: 1
Reputation: 173
I am not sure what output you are looking for. There is no key like '3w' in your yaml file
If desired output is like this:
a: team2
Then your code snippet should be like:
items = data.get('2w')
for item_roletype, value in items.iteritems():
print "%s: %s" % (item_roletype, value)
Upvotes: 0