Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
872 views
in Technique[技术] by (71.8m points)

dictionary - 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)

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

What would be the most minimal expression to replace it with?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Just use a for loop:

# 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; you'd end up with a list with None objects as a result, a list you discard immediately.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...