Skip to content
Advertisement

Pydantic – parse a list of objects from YAML configuration file

I want to read a list of objects from a YAML file:

JavaScript

For this data structure i created three nested models as follows:

JavaScript

My code to read the YAML config file looks as follows:

JavaScript

Now i want to unpack the values of the YAML to my model. For that i tried to unpack the values with the ** operator. I think im missing one more loop here though, but i can not get it work.

JavaScript

I would appreciate any help.

Update

So i played around with my model-structure a bit without using the YAML file. I dont quite get why the following throws an ValidationError:

Consider the following list of entries (thats the same data structure i would receive from my YAML file):

JavaScript

If i run the following simple loop, then Pydantic throws an ValidationError:

JavaScript

Error:

JavaScript

However, if the list only contains one entry dictionary, then it works:

JavaScript

Can someone explain this or what im doing wrong here?

Advertisement

Answer

In your update, the reason that the second case works but not the first is that the unpacking operator (**) takes a single dictionary object which contains all the necessary keys. In your first case, you had one dictionary with all the necessary info; in the second it is spread across two dicts and they can’t be unpacked together. One possible workaround would be to merge them into a single dictionary. But as far as I understand, a better solution would be to just change your YAML to provide this in the first place, by deleting the first two characters in each line:

JavaScript

and then:

JavaScript

Original answer:

There are a number of issues with your code, but I think what you’re trying to do is parse the YAML into a dictionary and instantiate an EntryValues from each item. That would look something like this:

JavaScript
Advertisement