简体   繁体   English

我应该如何从列表中删除所有不包含其值之一的字典?

[英]How should I remove all dicts from a list that have None as one of their values?

Suppose I have a list like so: 假设我有一个像这样的列表:

[{'name': 'Blah1', 'age': x}, {'name': 'Blah2', 'age': y}, {'name': None, 'age': None}]

It is guaranteed that both 'name' and 'age' values will either be filled or empty. 确保“姓名”和“年龄”值都将被填充或为空。

I tried this: 我尝试了这个:

for person_dict in list:
    if person_dict['name'] == None:
        list.remove(person_dict)

But obviously that does not work because the for loop skips over an index sometimes and ignores some blank people. 但是显然,这是行不通的,因为for循环有时会跳过索引而忽略一些空白的人。

I am relatively new to Python, and I am wondering if there is a list method that can target dicts with a certain value associated with a key. 我对Python还是比较陌生,我想知道是否有一个列表方法可以将与键关联的特定值的字典作为目标。

EDIT: Fixed tuple notation to list as comments pointed out 编辑:固定的元组符号列表作为注释指出

You can use list comprehension as a filter like this 您可以像这样使用列表理解作为过滤器

[c_dict for c_dict in dict_lst if all(c_dict[key] is not None for key in c_dict)]

This will make sure that you get only the dictionaries where all the values are not None . 这将确保您仅获得所有值都不为None的字典。

Just test for the presence of None in the dict's values to test ALL dict keys for the None value: 只需测试dict值中是否存在None即可测试所有dict键的None值:

>>> ToD=({'name': 'Blah1', 'age': 'x'}, {'name': 'Blah2', 'age': 'y'}, {'name': None, 'age': None})
>>> [e for e in ToD if None not in e.values()]
[{'age': 'x', 'name': 'Blah1'}, {'age': 'y', 'name': 'Blah2'}]

Or, use filter: 或者,使用过滤器:

>>> filter(lambda d: None not in d.values(), ToD)
({'age': 'x', 'name': 'Blah1'}, {'age': 'y', 'name': 'Blah2'})

Or, if it is a limited test to 'name': 或者,如果这是对“名称”的有限测试:

>>> filter(lambda d: d['name'], ToD)
({'age': 'x', 'name': 'Blah1'}, {'age': 'y', 'name': 'Blah2'})
for index,person_dict in enumerate(lis):
    if person_dict['name'] == None:
        del lis[index]

you can also try 你也可以尝试

lis=[person_dict  for person_dict in lis if person_dict['name'] != None]  

never use List as variable 永远不要将List用作变量

You can create new list with accepted data. 您可以使用接受的数据创建新列表。 If you have tuple then you have to create new list. 如果您有元组,则必须创建新列表。

List comprehension could be faster but this version is more readable for beginners. 列表理解可能会更快,但此版本对于初学者更易读。

data = ({'name': 'Blah1', 'age': 'x'}, {'name': 'Blah2', 'age': 'y'}, {'name': None, 'age': None})

new_data = []

for x in data:
    if x['name']: # if x['name'] is not None and x['name'] != ''
        new_data.append(x)

print new_data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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