Search code examples
pythonunpack

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.

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.