This is my YAML file (input.yaml
):
team_member:
name: Max
hobbies:
- Reading
team_leader:
name: Stuart
hobbies:
- dancing
I want to edit this YAML file to add more values in key 'hobbies', example:
team_member:
name: Max
hobbies:
- Reading
- Painting
team_leader:
name: Stuart
hobbies:
- Dancing
- Fishing
I tried to implement the code Anthon to fit my situation but it didn't helped at all, because the indention level of that YAML file is different from mine.
Example:
import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML()
# yaml.preserve_quotes = True
with open('input.yaml') as fp:
data = yaml.load(fp)
for elem in data:
if elem['name'] == 'Stuart':
elem['hobbies'] = ['Fishing']
break # no need to iterate further
yaml.dump(data, sys.stdout)
I get error "TypeError('string indices must be integers',)", I know this code might be completely wrong, but I am new to ruamel.yaml.
How to code this?
Thanks Anthon your code worked I have to edit this code as follows:
The thing missing form the error message displayed is the line number (I assume that it is 9). That points to the line
And if that doesn't give you a clue, the approach that I recommend in such cases is starting to add some
print
functions, so that you know what you are working on. Thefor
loop looks like:this prints
before the exception is thrown, and I hope that will make you realize your are not iterating over the elements (items) of a list, but over the keys of a dict (constructed from the root level mapping in your YAML). And the value associated with the key is the object having a key
name
and a keyhobbies
.So change the variable
elem
tokey
to make clear what you're handling and then proceed to work withvalue
, the value associated with that key instead ofelem
within that loop¹:This gives:
So we got rid of the exception, but the result is not exactly what you want. The element
dancing
for the key 'hobbies' is gone, because you assign a new (list) value to that key, whereas what you should do is append a single item to the list. We can also get rid of the print function by now:This will get you two items in the final sequence in the file. There is a few more things to address:
dancing
incorrect. To correct that, add a line handling the list if there is only one elementMax
, needs to be added (and that is why you need to get rid of thebreak
in your code)The final code would be like:
Which gives something quite close to what you wanted to get
¹Alternative for the first two lines:
for key, value in data.items()