简体   繁体   English

python删除列表理解中的字典键

[英]python delete dict keys in list comprehension

Why is the following expression, aiming at deleting multiple keys in a dict, invalid?为什么下面的表达式,旨在删除字典中的多个键,无效? ( event is a dict) event是一个字典)

[del event[key] for key in ['selected','actual','previous','forecast']]

What would be the most minimal expression to replace it with?用什么来代替它的最少表达是什么?

You should not use a list comprehension at all here.你不应该这里使用列表理解。 List comprehensions are great at building a list of values, and should not be used for general looping.列表推导式非常适合构建值列表,不应用于一般循环。 Using a list comprehension for the side-effects is a waste of memory on a perfectly good list object.对副作用使用列表理解是对完美列表对象的内存浪费。

List comprehensions are also expressions , so can only contain other expressions.列表推导式也是表达式,因此只能包含其他表达式。 del is a statement and can't be used inside an expression. del是一个语句,不能在表达式中使用。

Just use a for loop:只需使用for循环:

# use a tuple if you need a literal sequence; stored as a constant
# with the code object for fast loading
for key in ('selected', 'actual', 'previous', 'forecast'):
    del event[key]

or rebuild the dictionary with a dictionary comprehension:或使用字典理解重建字典:

# Use a set for fast membership testing, also stored as a constant
event = {k: v for k, v in event.items()
         if k not in {'selected', 'actual', 'previous', 'forecast'}}

The latter creates an entirely new dictionary, so other existing references to the same object won't see any changes.后者创建了一个全新的字典,因此对同一对象的其他现有引用不会看到任何更改。

If you must use key deletion in an expression, you can use object.__delitem__(key) , but this is not the place;如果必须在表达式中使用键删除,可以使用object.__delitem__(key) ,但这不是地方; you'd end up with a list with None objects as a result, a list you discard immediately.你最终会得到一个带有None对象的列表,一个你立即丢弃的列表。

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

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