Reputation: 61
I have a dictionary with values being a list of lists, e.g.:
Review_dict["0002"]
[['0002', '0292', '4', datetime.datetime(1998, 2, 27, 11, 1, 34)],
['0002', '0251', '5', datetime.datetime(1998, 2, 27, 12, 2, 24)],
['0002', '0050', '5', datetime.datetime(1998, 2, 27, 12, 3, 24)],
['0002', '0314', '1', datetime.datetime(1998, 3, 4, 10, 5, 45)]]
I want to remove certain list (within the "big" list), where 2nd element = '0251' or '0314'.
e.g. Review_dict["0002"] should become:
[['0002', '0292', '4', datetime.datetime(1998, 2, 27, 11, 1, 34)],
['0002', '0050', '5', datetime.datetime(1998, 2, 27, 12, 3, 24)]]
I have come up with this code but I want to know if there's a simpler/ more elegant way to do so.
remove = ['0251', '0314']
for key in list(Review_dict):
for ID in remove:
for num in range(len(Review_dict[key])):
if Review_dict[key][num][1] == ID:
del Review_dict[key][num]
Upvotes: 1
Views: 443
Reputation: 73460
You could just mutate the values of your outer dict:
remove = ['0251', '0314']
for v in Review_dict.values():
v[:] = (lst for lst in v if lst[1] not in remove)
Generally, one should not repeatedly remove from a list as each remove has linear complexity. Building from scratch is the better option. Whether this performs better depends on your data and how much there actually is to remove.
As a mutation, the slice assignment v[:] = ...
allows to ignore the keys of the outer dict entirely as you don't need to rebind them.
Upvotes: 1
Reputation: 560
You can use the filter method and pass a lambda function
Review_dict["0002"] = list(filter(lambda x:x[1] not in remove,Review_dict["0002"]))
Upvotes: 0
Reputation: 9572
You can use list comprehension as:
import datetime
Review_dict = dict()
Review_dict["0002"] = [['0002', '0292', '4', datetime.datetime(1998, 2, 27, 11, 1, 34)],
['0002', '0251', '5', datetime.datetime(1998, 2, 27, 12, 2, 24)],
['0002', '0050', '5', datetime.datetime(1998, 2, 27, 12, 3, 24)],
['0002', '0314', '1', datetime.datetime(1998, 3, 4, 10, 5, 45)]]
print(Review_dict)
Review_dict["0002"] = [l for l in Review_dict["0002"] if l[1] not in ['0251', '0314']]
print(Review_dict)
Output:
{'0002': [['0002', '0292', '4', datetime.datetime(1998, 2, 27, 11, 1, 34)], ['0002', '0050', '5', datetime.datetime(1998, 2, 27, 12, 3, 24)]]}
Here you only take elements which satisfy the criteria i.e. first element of inner list is not present in some other list of elements.
Upvotes: 0