0%

Reverse / invert a mapping

❓ 有一个字典长这样

1
my_map = {'a': 1, 'b': 2}

怎么反转成这样

1
inv_map = {1: 'a', 2: 'b'}

✔️ For Python 2.7.x

1
inv_map = {v: k for k, v in my_map.iteritems()}

For Python 3+:

1
inv_map = {v: k for k, v in my_map.items()}