3

I'm doing a simple yaml load and running into a small issue:

code:

with open(target, 'r') as stream:
    try:
        data = (yaml.load(stream))
    except Exception as exc:
        print (exc)

print(data)

First yaml file:

test:
  - foo: 1
  - bar: 2
test2:
  - foo: 1
  - bar: 2

Second yaml file:

foo: 1
bar: 2

I only need the values in the test group, so when I'm trying to access the data from the first yaml I use print(data['test']) which returns these values:

[{'foo': '1'}, {'bar': '2'}]

On the second one, I use the print(data) line and I get:

{'foo': '1'}, {'bar': '2'}

I know of a couple ways I could solve the problem, replacing the brackets with nothing or using an iterative loop to create a new object but that seems really convoluted. Is there a better way I can get the results I'm looking for without jumping through hoops and creating code that's harder to read?

Merakel
  • 167
  • 2
  • 2
  • 11
  • *I know of a couple ways I could solve the problem* What is problem here? – bhansa Nov 15 '17 at 19:02
  • 1
    The data is formatted as a list, and I want it as a dictionary without using a loop to get it in that format. – Merakel Nov 15 '17 at 19:34
  • @Merakel well, if you have a sequence of mappings in YAML, you'll get a list of dicts in python. you have to process the data yourself. or you could try to add the `!!omap` tag to the list in the first file, then you'll get back an `ordereddict` – tinita Nov 15 '17 at 19:48

2 Answers2

4

There is another way. Based on the yaml file syntax. Use this format instead in your yaml file.

test:
  foo: 1
  bar: 2
test2:
  - foo: 1
  - bar: 2

With this you can make a call to your foo test dictionary.

>>>print(data[test][foo])
1

This is because yaml reads "-" as list elements, while elements without the "-" are read as dictionary elements.

Apeasant
  • 177
  • 8
2

You will get a dictionary for the yaml data which you are reading.

{'test': [{'foo': 1}, {'bar': 2}], 'test2': [{'foo': 1}, {'bar': 2}]}

If you want to get the values of the test group as a dictionary you'll need to create the list of dicts into a dict manually.

dicta = {k:v for d in data['test'] for k, v in d.items()}
print(dicta) # {'foo': 1, 'bar': 2}
bhansa
  • 7,282
  • 3
  • 30
  • 55