Reputation: 686
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!
Upvotes: 2
Views: 11476
Reputation: 17044
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)]
Upvotes: 7
Reputation: 50540
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.
Upvotes: 3
Reputation: 9076
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}]}]
Upvotes: 4