pip install pyyaml
If you care about preserving the order of your mapping keys, the comment and the white space between the elements of the root-level sequence, e.g. because this file is under revision control, then you should use ruamel.yaml
(disclaimer: I am the author of that package).
Assuming your YAML document is in the file input.yaml
:
1 2 3 4 5 6 7 8 9 10 11 12 |
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'] == 'sense2': elem['value'] = 1234 break # no need to iterate further yaml.dump(data, sys.stdout) |
1 2 3 4 5 6 7 8 9 10 11 |
import yaml with open("data.yaml") as f: list_doc = yaml.safe_load(f) for sense in list_doc: if sense["name"] == "sense2": sense["value"] = 1234 with open("data.yaml", "w") as f: yaml.dump(list_doc, f) |