[英]check dicts in list and remove invalid dict
I want to check dicts in a list which format is : 我想检查列表中的字典,其格式为:
class
, subject
, teacher
class
, subject
, teacher
But I got weird result : 但是我得到了奇怪的结果:
In case 1 {'subject':'history','teacher':'Marry'}
is invalid 如果1
{'subject':'history','teacher':'Marry'}
无效
But the code didn't remove it ! 但是代码并没有将其删除!
And case 2 works well 案例2运作良好
Here is what I do : 这是我的工作:
# case 1
data_list = [{'class':'A','subject':'math','teacher':'Sam'},
{'class':'','subject':'','teacher':''},
{'subject':'history','teacher':'Marry'}]
# case 2
# data_list = [{'teacher': 'Marry', 'subject': 'D'}]
for data in data_list:
message={}
message['class'] = data.get('class',required_field) or blank_field
message['subject'] = data.get('subject',required_field) or blank_field
message['teacher'] = data.get('teacher',required_field) or blank_field
if required_field in message.values() or blank_field in message.values():
print "This dict need to be remove:{}".format(message)
data_list.remove(data)
print "#### final list ####"
print data_list
print "#### final list ####"
case 1 result : 情况1结果:
This dict need to be remove:{'teacher': 'This_field_may_not_be_blank', 'class': 'This_field_may_not_be_blank', 'subject': 'This_field_may_not_be_blank'}
#### final list ####
[{'teacher': 'Sam', 'class': 'A', 'subject': 'math'},
{'teacher': 'Marry', 'subject': 'history'}]
#### final list ####
case 2 result : 情况2结果:
This dict need to be remove:{'teacher': 'Marry', 'class': 'This_field_is_required', 'subject': 'D'}
#### final list ####
[]
#### final list ####
AJK has pointed out what's going wrong with your code, but you can also make it much shorter, and therefore easier to understand. AJK指出了代码出了什么问题,但是您也可以使其变得更短,因此更容易理解。 Bear in mind that the dictionary
get
method will return None
if the given key isn't in the dict, and that both None
and the empty string ""
evaluate to false. 请记住,如果给定键不在字典中,则字典的
get
方法将返回None
,并且None
和空字符串""
都将得出false。
So the easiest way to proceed would be to create a new list of the acceptable entries as follows: 因此,最简单的方法是创建一个新的可接受条目列表,如下所示:
result = []
for d in data_list:
if d.get("class") and d.get("subject") and d.get("teacher"):
result.append(d)
You can shorten this by using a comprehension: 您可以通过理解来缩短此时间:
result = [d for d in data_list
if d.get("class") and d.get("subject") and d.get("teacher")]
This is because you should never delete items from a list which you're iterating over using a for
. 这是因为您绝不应该从
for
迭代的列表中删除项目。
Here is a similar module : problem Deleting list items in a for loop (python) 这是一个类似的模块: 问题删除for循环中的列表项(python)
use th copy
module. 使用
copy
模块。 copied_list = copy.deepcopy(original_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.