简体   繁体   中英

Get a sub-set of a Python dictionary for a list

I have a list of dictionaries, like the one below:

[{'name':1, 'id':2, 'otherstuff':3}, {'name':2, 'id':3, 'otherstuff':1}, {'name':3, 'id':1, 'otherstuff':2}]

How do I extract only specific keys for each member into another list?

Trying to get this:

[{'name':1, 'id':2}, {'name':2, 'id':3}, {'name':3, 'id':1}]

Initialise a list of keys you need:

keys = {'name', 'id'}

Extract your key-value pairs in a list / dict comprehension.

filtered_data = [{k : x[k] for k in x.keys() & keys} for x in data] # thanks, vaultah!

The x.keys() & keys bit would work only in python3.x, since x.keys() is returned as a set , and the intersection operation ensures that no KeyError is raised if you try accessing a key that does not exist in that particular sub-dict.

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