Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load yaml list as dictionary

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?

like image 850
Merakel Avatar asked Oct 27 '25 03:10

Merakel


1 Answers

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.

like image 179
Apeasant Avatar answered Oct 28 '25 17:10

Apeasant