-1

I want to interchange keys and value in a given dictionary. For example:

dict = {1:'sandeep', 2: 'suresh', 3: 'pankaj'}

will become:

dict1 = {'sandeep': 1, 'suresh': 2, 'pankaj': 3}
jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
  • `{val: key for key, val in dict.items()}`? But you shouldn't name your own dictionary `dict`, and will you **always** have unique, hashable values? – jonrsharpe Apr 07 '15 at 10:32

2 Answers2

0

Using zip is probably better than a dictionary comprehension:

dict1 = dict(zip(dict1.values(), dict1.keys())) # better for beginners
Malik Brahimi
  • 15,933
  • 5
  • 33
  • 65
0
In [45]: d = {1:'sandeep',2 : 'suresh', 3: 'pankaj'}

In [46]: {(v, k) for k,v in d.iteritems()}
Out[46]: {'pankaj': 3, 'sandeep': 1, 'suresh': 2}

Note the use of d as the variable name instead of the built-in dict.

Also note that you are not guaranteed uniqueness and can loose entries:

In [47]: d = {1:'sandeep',2 : 'suresh', 3: 'pankaj', 4:'suresh'}

In [48]: {(v, k) for k,v in d.iteritems()}
Out[48]: {'pankaj': 3, 'sandeep': 1, 'suresh': 4}
Mike Bessonov
  • 566
  • 2
  • 8