Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unpack a list of dictionaries to an object in Python

I am not sure how to ask this as I’m not sure if I’m using the proper key words. I have a dictionaries in a variable x. I unpack (is that the right term?) to a object of type Org like so:

org = Org(**x)

where x is of the form:

{'user': 'joe@example.com', 'sk': 'meta_3', 'location': 'Dubai', 'name': 'Thomas'}

This works so far. I get an object org of type Org.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But my Q is: how do I handle if x is a list of dicts i.e. x is

[
  {'user': 'joe@example.com', 'sk': 'meta_3', 'location': 'Dubai', 'name': 'Thomas'},
  {'user': 'sam@example.com', 'sk': 'meta_4', 'location': 'Spain', 'name': 'Sam'}
]

How do I unpack that to a list of Org objects?

>Solution :

If x_list is your list containing dicts:

org_list = []
for x in x_list:
    org = Org(**x)
    org_list.append(org)

Now you have a list org_list that contains all created Org objects.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading