1

This is a code for switching between the key and value in a dictionary:

for k in d:
    d[d[k]] = k
    d.pop(k)

The problem with this code that it makes more operations that it should make, and for some inputs return the wrong result

what is the reason of this problem?

James
  • 32,991
  • 4
  • 47
  • 70
  • Possible duplicate of [Modifying a Python dict while iterating over it](http://stackoverflow.com/questions/6777485/modifying-a-python-dict-while-iterating-over-it) –  Apr 14 '17 at 14:16

2 Answers2

3

You are adding values to a dictionary as you are iterating through it. Generally this is a bad idea. It is better to construct a new dictionary using dictionary comprehension.

new_d = {v:k for k,v in d.items()}
James
  • 32,991
  • 4
  • 47
  • 70
3

The problem is that you're changing the dictionary while iterating over it, and who knows what problems that causes.

Note that generally speaking you can't reverse dictionaries: keys must be unique and hashable, but values don't have to be. I'm assuming your dictionaries have unique hashable values so that it's at least possible.

Then I would use a dictionary comprehension to create a new dictionary, and assign that:

d = {value: key for (key, value) in d.items()}
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79