Skip to content Skip to sidebar Skip to footer

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']] Wha

Solution 1:

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:

# useatupleifyouneedaliteralsequence; storedasaconstant
# withthecodeobjectforfastloadingforkeyin ('selected', 'actual', 'previous', 'forecast'):
    delevent[key]

or rebuild the dictionary with a dictionary comprehension:

# Use a set for fast membership testing, also stored as a constantevent = {k: v for k, v inevent.items()
         if k notin {'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.

Post a Comment for "Python Delete Dict Keys In List Comprehension"