[英]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. 您可以使用filter()
函数。 It will take 2 arguments filter(function, iterable)
. 它需要两个参数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)]
filter(function, iterable)
等效于[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 = ...
). 重要的是第二行( 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. 如果没有,则将其跳过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.