I want to filter out some elements from a Python dictionary. Which way is more preferable? My dictionary is quite big...
Below is however an example code with a smaller data set:
d = {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
1st
d = {i:v for i, v in d.items() if i%2 == 0}
2nd
list_to_del = []
for i in d.keys():
if i%2 == 0:
list_to_del.append(d)
for i in list_to_del:
del d[i]
list_to_del.clear()
Is there any risk of memory leak in the first case?
Honestly, your first one looks exactly how I would do it. However, if you do need to just iterate over the entries and filter, try just leaving it in iterator form.
entries = filter(lambda x: x[1] % 2 == 0, d.items())