Python 3 how to change keys and values of dictionary
If you want to exchange keys and values of a python dictionary you can use list comprehensions for this task. The easiest and obvious solution is one liner. This solution should work for Python 3. For Python 2 there is a small difference in the list comprehension syntax:
Python 3
countries_dict = {'Brasilia': 'Brazil', 'Rome': 'Italy', 'Cairo': 'Egypt', 'Ottawa': 'Canada', 'Beijing': 'China', 'Panama City': 'Panama', 'Mexico City': 'Mexico'}
dict_rev = {v: k for k, v in countries_dict.items()}
print(dict_rev)
result is:
{'Brazil': 'Brasilia', 'Canada': 'Ottawa', 'Italy': 'Rome', 'Mexico': 'Mexico City', 'Egypt': 'Cairo', 'Panama': 'Panama City', 'China': 'Beijing'}
as a result you can find that keys and values are exchanged and the order is preserved. Having in mind that order for dictionaries is not really important.
For python 2 you can use the previous version or use the one below:
Python 2
countries_dict = {'Brasilia': 'Brazil', 'Rome': 'Italy', 'Cairo': 'Egypt', 'Ottawa': 'Canada', 'Beijing': 'China', 'Panama City': 'Panama', 'Mexico City': 'Mexico'}
dict_rev = {v: k for k, v in countries_dict.iteritems()}
print(dict_rev)
The result is exactly the same:
{'Brazil': 'Brasilia', 'Canada': 'Ottawa', 'Italy': 'Rome', 'Mexico': 'Mexico City', 'Egypt': 'Cairo', 'Panama': 'Panama City', 'China': 'Beijing'}
Here is the difference between both versions:
- dict.items() returns a list of 2-tuples ([(key, value), (key, value), ...]) - and takes more space and time initially, but accessing each element is fast
- dict.iteritems() is a generator that yields 2-tuples - takes less space and time initially, but a bit more time in generating each element