I have two dictionaries, I need to remove the keys from dictionary 1 which don't occur in dictionary 2. This is my attempt:
d1 = {'id1':1,
'id2':1,
'id3':1,
'id4':1}
d2 = {'id1':0,
'id2':0,
'id3':0,
'idnew':0}
for k in (d1.keys()-d2.keys()):
del d1[k]
print (d1)
prints:
{'id1': 1, 'id2': 1, 'id3': 1}
My question is: Is this the fastest/most memory efficient way to do this? or does it construct sets which will take up more memory than required to do something like this
My 2nd attempt:
d1 = {k:v for k,v in d1.items() if k in d2}