0

I have two dictionaries with keys as string and values as integer:

ground = {"url1":1,"url2":2,....}
prediction = {"url1":5,"url2":3,....}

The thing I want to do is to delete key in ground if it does not exist in prediction.

I wrote the easiest thing that came to my head:

for key in ground:        
    if key not in prediction:
        del ground[key]

and also tried this:

for key in ground:
    if not key in prediction.keys():
        del ground[key]

Neither worked. How can I achieve the goal?

Farhan.K
  • 3,425
  • 2
  • 15
  • 26
Stanislav Barabanov
  • 879
  • 1
  • 8
  • 13

3 Answers3

2

You could use a dictionary comprehension to create a new dictionary:

ground = {k: ground[k] for k in ground if k in prediction}

Or iterate over the keys of the ground dictionary using ground.keys() in Python 2, or list(ground.keys()) in Python 3 (also works in Python 2). This returns a new list which is not affected when keys are removed from the ground dictionary:

for k in list(ground.keys()):
    if k not in prediction:
        del ground[k]
mhawke
  • 84,695
  • 9
  • 117
  • 138
0

You loop over the dict and delete a key inside the same loop. That's why it may not work. Try:

pred_set = set(prediction.keys())
g_set = set(ground.keys())
for key in g_set - pred_set:
    del ground[key]
loutre
  • 874
  • 8
  • 16
0

Your second attempt works fine in Python 2. In Python 3, keys() is a view rather than a list, so would give the same error as the first: dictionary changed size during iteration. To fix this, convert it to a list first:

for key in list(ground.keys()):
  if key not in prediction:
    del ground[key]
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895