David542
David542

Reputation: 110502

How to do a one-line dict delete operation

Is there a way to do the following in one line?

[del item for item in new_json if item['Country'] in countries_to_remove]

The above gives me a SyntaxError.

Upvotes: 2

Views: 388

Answers (2)

thefourtheye
thefourtheye

Reputation: 239653

del is a statement and you cannot use that as an expression in list comprehenstion. That is why you are getting a SyntaxError.

You can use list comprehension to create a new list, without the elements you don't want, like this

[item for item in new_json if item['Country'] not in countries_to_remove]

This is actually equivalent to,

result = []
for item in new_json:
    if item['Country'] not in countries_to_remove:
        result.append(item)

This kind of operation is called filtering a list and you can use the builtin filter function, like this

list(filter(lambda x: x['Country'] not in countries_to_remove, new_json))

As suggested by mgilson in the comments section, if you just want to mutate the original list, then you can use slicing assignment, like this

new_json[:] = [x for x in new_json if x['Country'] not in countries_to_remove]

Upvotes: 4

Anand S Kumar
Anand S Kumar

Reputation: 90999

del is a statement in python, and you cannot have statements inside list comprehension (You can only have expressions there). Why not just create new_json as a new list or dictionary that does not include the items you want to delete. Example =

new_json = [item for item in new_json if item['Country'] not in countries_to_remove]

Upvotes: 4

Related Questions