Search code examples
python-3.xyamlpyyaml

Python3 - YAML not correctly appending values in list


Snippet of the .yml file:

- hosts: arbiters
  roles:
    - role: roles/arbiters
      vars:
        machines:
          arb-1:
            - repset: r-11
              mongoversion: 4.2
              port: 27017
            - repset: r-17
              mongoversion: 4.2
              port: 27018

I want to append sub-keys with values using Python:

            - repset: my_own_value
              mongoversion: 40000
              port: 1

The following code works partially

data[0]['roles'][0]['vars']['machines']['arb-2'] = dict(mongoversion='40000', port='1', repset='my_own_value')

gives

'arb-2': {'mongoversion': 40000,
          'port': '1',
          'repset': 'my_own_value'}

This is incorrect, as I want to append, instead of replace. When I use the += operator, instead of =, it gives:

'arb-2': [{'mongoversion': 4.2,
           'port': 27017,
           'repset': 'r-10'},
          {'mongoversion': 4.2,
           'port': 27018,
           'repset': 'r-16'},
           'mongoversion',
           'port',
           'repset']

Now, the values are missing. I've followed the answer as described here, and tried to play around with several settings, but I don't seem to succeed.


Solution

  • The problem is, your element ['arb-1'] isn't of type dict, it is of type list. So actually you should do the following:

    data[0]['roles'][0]['vars']['machines']['arb-2'].append({'mongoversion'="v40000",'port'=1,'repset'="my_own_value"})
    

    or in short

    data["some"]["path"].append({'your':"object",'values':"here"})
    

    -- edit --

    Here is a complete test program. Dependency can be installed with pip install pyyaml.

    import yaml
    
    yaml_doc = """
      a: 1
      b:
        c:
          - a: b
            e: f
          - c: d
        d: 4
    """
    
    doc = yaml.load(yaml_doc, Loader=yaml.FullLoader)
    
    print(type(doc["b"]["c"]))
    print doc
    
    doc["b"]["c"].append({"x":2,"w":"i","u":'t'})
    print doc