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 03:59

I wrote this with the help of cycle 'for' and method '.get()' and I changed the name 'map' of the dictionary to 'map1' because 'map' is a function.

def dict_invert(map1):
    inv_map = {} # new dictionary
    for key in map1.keys():
        inv_map[map1.get(key)] = key
    return inv_map
查看更多
刘海飞了
3楼-- · 2018-12-31 04:00

If values aren't unique AND may be a hash (one dimension):

for k, v in myDict.items():
    if len(v) > 1:
        for item in v:
            invDict[item] = invDict.get(item, [])
            invDict[item].append(k)
    else:
        invDict[v] = invDict.get(v, [])
        invDict[v].append(k)

And with a recursion if you need to dig deeper then just one dimension:

def digList(lst):
    temp = []
    for item in lst:
        if type(item) is list:
            temp.append(digList(item))
        else:
            temp.append(item)
    return set(temp)

for k, v in myDict.items():
    if type(v) is list:
        items = digList(v)
        for item in items:
            invDict[item] = invDict.get(item, [])
            invDict[item].append(k)
    else:
        invDict[v] = invDict.get(v, [])
        invDict[v].append(k)
查看更多
余欢
4楼-- · 2018-12-31 04:01
def inverse_mapping(f):
    return f.__class__(map(reversed, f.items()))
查看更多
梦该遗忘
5楼-- · 2018-12-31 04:01

As per my comment to the question. I think the easiest and one liner which works for both Python2 and Python 3 will be

dict(zip(inv_map.values(), inv_map.keys()))
查看更多
姐姐魅力值爆表
6楼-- · 2018-12-31 04:02

If the values in my_map aren't unique:

inv_map = {}
for k, v in my_map.iteritems():
    inv_map[v] = inv_map.get(v, [])
    inv_map[v].append(k)
查看更多
像晚风撩人
7楼-- · 2018-12-31 04:02

Combination of list and dictionary comprehension. Can handle duplicate keys

{v:[i for i in d.keys() if d[i] == v ] for k,v in d.items()}
查看更多
登录 后发表回答