I have an extension question to remove dictionary from list , except that I have a list of dictionary keys I would like to remove from the list.
So, I have something like:
a=[{'id': 1, 'name': 'paul'},{'id': 2, 'name': 'john'},{'id': 3, 'name': 'john2'},{'id': 4, 'name': 'johnasc'}]
now, I have a del_list, like so:
del_id_list=[2,4]
what is the efficient way (assuming list a
is LARGE) to delete dictionaries with id
from del_list
from a
?
one way, recreating the list using a list comprehension (and declaring del_id_list
as a set
for faster lookup):
a=[{'id': 1, 'name': 'paul'},{'id': 2, 'name': 'john'},{'id': 3, 'name': 'john2'},{'id': 4, 'name': 'johnasc'}]
del_id_list={2,4}
new_a = [d for d in a if d['id'] not in del_id_list]
result:
[{'id': 1, 'name': 'paul'}, {'id': 3, 'name': 'john2'}]
Get acquainted with filter :
result = filter(lambda x: x['id'] not in del_id_list,a)
EDIT:
Regarding the del_id_list
itself, if it's long you may want to consider the complexity of the in
statement. Maybe a set
and even a dict
(with arbitrary value) would be better. Check this .
EDIT 2: As @Jean correctly points out, this is a iteration sequence in Py3. Just add list:
result = list(filter(lambda x: x['id'] not in del_id_list,a))
sourceList = [{'id': 1, 'name': 'paul'},{'id': 2, 'name': 'john'},{'id': 3, 'name': 'john2'},{'id': 4, 'name': 'johnasc'}]
del_id_list = [2,4]
for itemDict in sourceList:
if itemDict['id'] in del_id_list:
sourceList.remove(itemDict)
print(sourceList)
Result -> [{'name': 'paul', 'id': 1}, {'name': 'john2', 'id': 3}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.