2

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}
ragardner
  • 1,503
  • 2
  • 16
  • 36

3 Answers3

1

filter and dict comprehension might be a good way to go for such a task, although this issue is easy to solve without as well.

 filtered_d = {k:d1[k] for k in filter(lambda k: k in d2, d1)}
olisch
  • 850
  • 6
  • 11
0

Dict comprehension can have a perfomance hit when dictionaries a large. You can remove them just iterating over list with for loop:

for key in set(d1) -set(d2):
    del d1[key]

or if you know that your dicts will be small, you can use dict comprehension.

d1 = {k: v for k, v in d1.items() if k in d2}

ailin
  • 454
  • 4
  • 14
0

Your solve is good because : the fastest/most memory efficient issues come from type of values and sized . This can be see and set with a python debugger.