Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 408
jim jarnac Avatar asked Apr 26 '17 11:04

jim jarnac


People also ask

How do I remove a dictionary key from a list?

Remove multiple keys from a dictionary using pop() In this method, we just use the Python pop() function which is used to remove a single key along with the list comprehension which iterates for the entire list to perform the remove operation.

Can you remove a key from a dictionary python?

To remove a key from a dictionary in Python, use the pop() method or the “del” keyword. Both methods work the same in that they remove keys from a dictionary. The pop() method accepts a key name as argument whereas “del” accepts a dictionary item after the del keyword.

How remove key from dictionary while iterating?

First, you need to convert the dictionary keys to a list using the list(dict. keys()) method. During each iteration, you can check if the value of a key is equal to the desired value. If it is True , you can issue the del statement to delete the key.


1 Answers

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.

like image 131
Martijn Pieters Avatar answered Oct 16 '22 03:10

Martijn Pieters