-1

I'm trying to write something into a .yaml file but am confused by the documentation. It there says the following:

Block mapping can be nested:

# YAML
hero:
  hp: 34
  sp: 8
  level: 4
orc:
  hp: 12
  sp: 0
  level: 2

# Python
{'hero': {'hp': 34, 'sp': 8, 'level': 4}, 'orc': {'hp': 12, 'sp': 0, 'level': 2}}

So I am trying to get a similar result with the yaml file looking like this in the end:

User1:
  name: 'name1'
  id: 001
  strikes: 1
User2:
  name: 'name2'
  id: 002
  strikes: 3

When I try to use what was used in the example from the docs, it results in this:

User1: {id: '001', name: name1, strikes: 1}
User2: {id: '002', name: name2, strikes: 3}

For this, I used the following code:

strikes = {'User1': {'name': 'name1', 'id': '001', 'strikes': 1}, 'User2': {'name': 'name2', 'id': '002', 'strikes': 3}}

with open(path + "/strikes.yml", 'w+') as stream:
    yaml.dump(strikes, stream)
Lithimlin
  • 542
  • 1
  • 6
  • 24
  • Is that actually a *problem*? You can interact with an `OrderedDict` in the same way you do with a vanilla `dict`. – jonrsharpe May 01 '18 at 11:33
  • Well, I'm mostly trying to write a yaml file with python so it ***results*** in the yaml example from the docs – Lithimlin May 01 '18 at 11:35
  • 1
    But the thing you're asking about is the behaviour when you *read* from a file, no? Have you actually tried writing, from vanilla dictionaries or ordered ones? Aside from any ordering issues in the former case, was that actually a problem? Give a [mcve]. – jonrsharpe May 01 '18 at 11:36
  • Yes, sorry. I realize now that my question is not very clear. Give me a moment to fix that, please. – Lithimlin May 01 '18 at 11:38
  • Edited my question to be more clear, hopefully – Lithimlin May 01 '18 at 11:45
  • Again, please give a [mcve]. Include the appropriate code in your question. Also note that the docs you quote say at the top that they're left for historical purposes, so may not be reliable. – jonrsharpe May 01 '18 at 11:46
  • The quoted docs are the only ones I could find though, as the github only links back to them. – Lithimlin May 01 '18 at 11:51

1 Answers1

4

PyYAML by default, does write out composite leaf nodes in flow-style and the rest in block-style.

If you don't want that, i.e. want everything to be block-style, use safe_dump(data, default_flow_style=False):

import sys
import yaml


strikes = {'User1': {'name': 'name1', 'id': '001', 'strikes': 1}, 'User2': {'name': 'name2', 'id': '002', 'strikes': 3}}

yaml.safe_dump(strikes, sys.stdout, default_flow_style=False)

gives:

User1:
  id: '001'
  name: name1
  strikes: 1
User2:
  id: '002'
  name: name2
  strikes: 3

There is no reason to use yaml.dump() instead of yaml.safe_dump() (and I definately hope you are not using yaml.load() instead of yaml.safe_load())

Anthon
  • 69,918
  • 32
  • 186
  • 246