Search code examples
pythonyamlfile-handlingpyyaml

How to read the yaml file as dictionary and update value using python


I need to write function to read the YAML file and update the specific value. The YAML file is dictionary,

sample :
    test_example:
    parent:
      attribute_1: 2
      attribute_2: 2
    parent2:
      childList:
        - group: 2
          type: "test"
          track_int:
            - key_1: 3
              key_2: 25
              state: present
          state: present
        - group: 4
          typr: "old"
          track_int:
            - key_1: 3
              key_2: 25
              state: present
          state: present

Now I need to write function to pass the key and it should replace the value for specific value ex - update the test_example["parent2"]["childList"][0]["group"] to 4 and update test_example["parent"]["attribute_2"] to 5

How can I do that?


Solution

  • If you want to preserve the rest of the input file as-is, including the superfluous quotes around "test" and "old" and the offset of the dash in your sequence indent then your only real option is to use ruamel.yaml (disclaimer: I am the author of that package):

    import sys
    import ruamel.yaml
    
    yaml = ruamel.yaml.YAML()
    yaml.preserve_quotes = True
    yaml.indent(mapping=4, sequence=4, offset=2)
    
    with open('input.yaml') as fp:
        data = yaml.load(fp)
    
    test_example = data['sample']
    test_example["parent2"]["childList"][0]["group"] =4
    test_example["parent"]["attribute_2"] = 5
    yaml.dump(data, sys.stdout)
    

    gives:

    sample:
        test_example:
        parent:
            attribute_1: 2
            attribute_2: 5
        parent2:
            childList:
              - group: 4
                type: "test"
                track_int:
                  - key_1: 3
                    key_2: 25
                    state: present
                state: present
              - group: 4
                typr: "old"
                track_int:
                  - key_1: 3
                    key_2: 25
                    state: present
                state: present
    

    The naming of your Python test_example of course cannot correspond to the test_example of your input file. That gets loaded as None (assuming your input is really indented as you presented your YAML document).