Python reverse / invert a mapping

2018-12-31 03:53发布

Given a dictionary like so:

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

How can one invert this map to get:

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

EDITOR NOTE: map changed to my_map to avoid conflicts with the built-in function, map. Some comments may be affected below.

30条回答
大哥的爱人
2楼-- · 2018-12-31 04:05

Using zip

inv_map = dict(zip(my_map.values(), my_map.keys()))
查看更多
浅入江南
3楼-- · 2018-12-31 04:06

I would do it that way in python 2.

inv_map = {my_map[x] : x for x in my_map}
查看更多
一个人的天荒地老
4楼-- · 2018-12-31 04:06

This is not the best solution, but it works. Let's say the dictionary we want to reverse is:

dictionary = {'a': 1, 'b': 2, 'c': 3}, then:

dictionary = {'a': 1, 'b': 2, 'c': 3}
reverse_dictionary = {}
for index, val in enumerate(list(dictionary.values())):
    reverse_dictionary[val] = list(dictionary.keys())[index]

The output of reverse_dictionary, should be {1: 'a', 2: 'b', 3: 'c'}

查看更多
无色无味的生活
5楼-- · 2018-12-31 04:07

Assuming that the values in the dict are unique:

dict((v, k) for k, v in my_map.iteritems())
查看更多
浪荡孟婆
6楼-- · 2018-12-31 04:07

Try this for python 2.7/3.x

inv_map={};
for i in my_map:
    inv_map[my_map[i]]=i    
print inv_map
查看更多
不流泪的眼
7楼-- · 2018-12-31 04:07
  def reverse_dictionary(input_dict):
      out = {}
      for v in input_dict.values():  
          for value in v:
              if value not in out:
                  out[value.lower()] = []

      for i in input_dict:
          for j in out:
              if j in map (lambda x : x.lower(),input_dict[i]):
                  out[j].append(i.lower())
                  out[j].sort()
      return out

this code do like this:

r = reverse_dictionary({'Accurate': ['exact', 'precise'], 'exact': ['precise'], 'astute': ['Smart', 'clever'], 'smart': ['clever', 'bright', 'talented']})

print(r)

{'precise': ['accurate', 'exact'], 'clever': ['astute', 'smart'], 'talented': ['smart'], 'bright': ['smart'], 'exact': ['accurate'], 'smart': ['astute']}
查看更多
登录 后发表回答