Search code examples
pythonyamlpyyaml

PyYAML dumps Python dictionary with tags


I don't understand why yaml.dump adds tags and weird informations into result:

Source file.yml content is :

ssh_keys:
  user1:
    - key: key1
      state: state1

I want to add to the file the following key :

key_to_add = {
  'key': key2,
  'state': state2
}

Here is my code :

import yaml 

with open('file.yml', 'r') as file:
  data = yaml.load(file)
 
print(key_to_add)
data['ssh_keys']['user1'].append(key_to_add)
print(data)
print(type(data))
print(yaml.dump(data))

The unexpected result:

{'key': 'key2', 'state': 'state2'}
{'ssh_keys': {'user1': [{'key': 'key1', 'state': 'state1'}, {'key': 'key2', 'state': 'state2'}]}}
<class 'dict'>
ssh_keys:
  user1:
    - key: 'key1'
      state: 'state1'
    - key: !!python/object/new:ansible.parsing.yaml.objects.AnsibleUnicode
        args:
        - key2
        state:
          _column_number: 26
          _data_source: /home/...........
          _line_number: 34  
      state: !!python/object/new:ansible.parsing.yaml.objects.AnsibleUnicode
        args:
        - state2
        state:
          _column_number: 24
          _data_source: /home/...........
          _line_number: 35

I was expecting the following result:

ssh_keys:
  user1:
    - key: 'key1'
      state: 'state1'
    - key: 'key2'
      state: 'state2'

Solution

  • Took a brief look at pyyaml docs and figured out below code generates desired output

    import yaml
    try:
        from yaml import CLoader as Loader, CDumper as Dumper
    except ImportError:
        from yaml import Loader, Dumper
    
    with open('file.yml', 'r') as file:
        data = yaml.load(file, Loader=Loader)
    
    key_to_add = {
        'key': 15,
        'state': 166
    }
    print(key_to_add)
    data['ssh_keys']['user1'].append(key_to_add)
    print(data)
    print(type(data))
    print(yaml.dump(data, Dumper=Dumper))