简体   繁体   中英

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 ie 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM