Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyYAML dumping invalid YAML unless param includes an array

I might be missing something obvious but I am having this behavior in Python 2 and 3. I installed yaml using pip (for both python versions): pip3 install pyyaml

Only the 2nd print statement is valid YAML, only because I included the aa key to the dict:

>>> import yaml

>>> print(yaml.dump({'name': 'wut', 'age': 'wise'}))
{age: wise, name: wut}

>>> print(yaml.dump({'name': 'wut', 'age': 'wise', 'aa': []}))
aa: []
age: wise
name: wut

>>>
like image 887
Raynard Avatar asked Aug 07 '26 18:08

Raynard


1 Answers

I'm not really sure what your question is here, and I don't think this is an issue (I see the same behavior in PYYAML on Python 2.7.3 in Windows 7). At least, the output of the dump actions appears to be correct in both cases.

The first yaml.dump seems to be valid, i.e., I can load that output:

>>> print(yaml.load("{age: wise, name: wut}"))
{'name': 'wut', 'age': 'wise'}

If you don't like that particular form of output from the dump action, please refer to the PYYAML documentation. PYYAML automagically chooses the flow style based on the YAML content your trying to dump; in this case it seems to treat the list as a nested collection and shows the dump in a different way.

If you want the first print statement to output the data in the same way as the second, you can force PYYAML to not use that flow style like this:

>>> print(yaml.dump({'name': 'wut', 'age': 'wise'}, default_flow_style=False))
age: wise
name: wut
like image 195
Raceyman Avatar answered Aug 10 '26 09:08

Raceyman