How to change keys to values ​​in a dictionary

Possible duplicate:
Python: best way to exchange keys with values ​​in a dictionary?

Suppose I need to swap keys for values ​​in a dictionary.

This is what I mean (suppose the value is unique):

>>> my_dict = {'x':1, 'y':2, 'z':3} >>> my_dict2 = {} >>> for key, val in my_dict.items(): my_dict2[val] = key 

Is there any other effective way to do this?

+28
python
Jul 06 '09 at 15:41
source share

No one has answered this question yet.

See similar questions:

77
Python: best way to exchange keys with values ​​in a dictionary?
5
Key-value pairs in a dictionary
3
Improving key exchange with values ​​in a dictionary?
3
Sharing Dictionary Content

or similar:

4268
How to combine two dictionaries in one expression?
3428
How to sort a dictionary by value?
2683
Check if the given key exists in the dictionary
2679
Iterate over dictionaries using 'for' loops
2369
Add new keys to the dictionary?
2030
How do you break a list into pieces with uniform size?
1531
Calling a module function using its name (string)
1491
How to check if a string is a number (float)?
1242
Using * args and ** kwargs
907
How to get the number of lines cheap in Python?



All Articles