[Python](EN) Exchange key and value each other in dictionary
Exchange key and value each other in dictionary
Environment and Prerequisite
- Python
Exchange key and value each other
Use List Comprehensions
- Example
dict((value, key) for (key, value) in d.items())
- Example
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> d = dict((value, key) for (key, value) in d.items())
>>> d
{1: 'a', 2: 'b', 3: 'c'}
Use lambda
- Example
dict(map(lambda e : (e[1], e[0]), d.items()))
- Example
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> d = dict(map(lambda e : (e[1], e[0]), d.items()))
>>> d
{1: 'a', 2: 'b', 3: 'c'}