简体   繁体   中英

Filter a list of dictionaries in Python based on key

I would need to filter a list of dictionaries to only retain dictionaries which have a key called "children". Here is an example of list:

[{u'id': 5650, u'children': [{u'id': 4635}]}, {u'id': 5648, u'children': [{u'id': 67}, {u'id': 77}]}, {u'id': 5649}]

And here is what I would need to obtain:

[{u'id': 5650, u'children': [{u'id': 4635}]}, {u'id': 5648, u'children': [{u'id': 67}, {u'id': 77}]}]

Here is what I have tried:

dict((k, data[k]) for k in keys if k in data)

And what I obtain, which is not good:

[{u'children': [{u'id': 4635}]}, {u'children': [{u'id': 67}, {u'id': 77}]}, {}]

Any clue? Thanks in advance!

You can use filter() function. It will take 2 arguments filter(function, iterable) . Only those values will be considered which the function returns.

a=[{u'id': 5650, u'children': [{u'id': 4635}]},
   {u'id': 5648, u'children': [{u'id': 67}, {u'id': 77}]},
   {u'id': 5649}]

print filter(lambda x: 'children' in x, a)

Output:

[{u'id': 5650, u'children': [{u'id': 4635}]},
 {u'id': 5648, u'children': [{u'id': 67}, {u'id': 77}]}]

filter(function, iterable) is equivalent to [item for item in iterable if function(item)]

How's this?

dict_list = [{u'id': 5650, u'children': [{u'id': 4635}]}, {u'id': 5648, u'children': [{u'id': 67}, {u'id': 77}]}, {u'id': 5649}]

filtered = [d for d in dict_list if 'children' in d]

print(filtered)

Output

[{'id': 5650, 'children': [{'id': 4635}]}, {'id': 5648, 'children': [{'id': 67}, {'id': 77}]}]
l = [{u'id': 5650, u'children': [{u'id': 4635}]}, {u'id': 5648, u'children': [{u'id': 67}, {u'id': 77}]}, {u'id': 5649}]
d = [k for k in l if 'children' in k]
print (d)

Outputs:

[{u'id': 5650, u'children': [{u'id': 4635}]}, {u'id': 5648, u'children': [{u'id': 67}, {u'id': 77}]}]

The important line is the second line ( d = ... ). This is looping through each dictionary in the list and checking if there is a 'children' key. If there is, it is added to the list. If there is not, it's skipped.

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