CodingNinja
CodingNinja

Reputation: 109

Add value for variable in existing yaml file using python

Input.yml:

version: "3.2"
Animal:
  mamal:
    wild:
      - Tiger
      - Lion
    Pet:
      - Dog
      - Cat
  Bird:
    wild:
      - Peacock
      - Ostrich
    Pet:
      - Parrot
      - Dove
Fish:
  Sea:
    - Shark
    - whale

Need to add some more values for the pet variable in the Bird section

Python Code I am trying :

import yaml

with open ('input.yml', 'r') as read_file:
    contents = yaml.safe_load_all(read_file)
    contents1=list(contents)
    for k in contents1:
        if 'Animal' in contents1[k]:
            contents1['Bird']['Pet'].append(['Duck','swan'])

Anyone, please help how to update the YAML files using python.

Upvotes: 2

Views: 1933

Answers (1)

ScottC
ScottC

Reputation: 4105

Try using the extend() function to extend the list of interest.
You can access the Animal > Bird > Pet list by using:

contents['Animal']['Bird']['Pet']

Here is some example code that:

  • safe_load the input.yml file into the contents variable
  • extend the list of interest as descibed above
  • write to a new yaml file called output.yml
  • use sort_keys=False to preserve the same order as original file.

Code:

import yaml

# Read the YAML file
with open ('input.yml', 'r') as read_file:
    contents = yaml.safe_load(read_file)

# Update the Animal > Bird > Pet list    
contents['Animal']['Bird']['Pet'].extend(['Duck','Swan'])

# Write the YAML file with sort_keys=False to retain same order
with open('output.yml', 'w') as write_file:
    yaml.dump(contents, write_file, sort_keys=False)

output.yml:

version: '3.2'
Animal:
  mamal:
    wild:
    - Tiger
    - Lion
    Pet:
    - Dog
    - Cat
  Bird:
    wild:
    - Peacock
    - Ostrich
    Pet:
    - Parrot
    - Dove
    - Duck
    - Swan
Fish:
  Sea:
  - Shark
  - whale

Note:

If you wish to just update the input.yml file, then just write to that file instead of output.yml

Upvotes: 2

Related Questions