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}
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}
Using zip
is probably better than a dictionary comprehension:
dict1 = dict(zip(dict1.values(), dict1.keys())) # better for beginners
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}