Joseph
Joseph

Reputation: 2245

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': '[email protected]', 'sk': 'meta_3', 'location': 'Dubai', 'name': 'Thomas'}

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

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

[
  {'user': '[email protected]', 'sk': 'meta_3', 'location': 'Dubai', 'name': 'Thomas'},
  {'user': '[email protected]', 'sk': 'meta_4', 'location': 'Spain', 'name': 'Sam'}
]

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

Upvotes: 1

Views: 541

Answers (1)

Damiaan
Damiaan

Reputation: 887

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.

Upvotes: 2

Related Questions