给定一本这样的字典:

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

如何将此映射颠倒得到:

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

当前回答

我会在python2中这样做。

inv_map = {my_map[x] : x for x in my_map}

其他回答

这扩展了Robert的回答,适用于字典中的值不是唯一的情况。

class ReversibleDict(dict):
    # Ref: https://stackoverflow.com/a/13057382/
    def reversed(self):
        """
        Return a reversed dict, with common values in the original dict
        grouped into a list in the returned dict.

        Example:
        >>> d = ReversibleDict({'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2})
        >>> d.reversed()
        {1: ['d'], 2: ['c', 'b', 'f'], 3: ['a', 'e']}
        """
        
        revdict = {}
        for k, v in self.items():
            revdict.setdefault(v, []).append(k)
        return revdict

该实现的局限性在于您不能使用反转两次并获得原始数据。它本身不是对称的。它是用Python 2.6测试的。这是一个用例,我是如何使用打印结果字典。

如果你更喜欢使用集合而不是列表,并且可能存在无序的应用程序,这是有意义的,而不是setdefault(v, []).append(k),使用setdefault(v, set()).add(k)。

例如,你有以下字典:

my_dict = {'a': 'fire', 'b': 'ice', 'c': 'fire', 'd': 'water'}

你想要得到这样一个倒立的形式

inverted_dict = {'fire': ['a', 'c'], 'ice': ['b'], 'water': ['d']}

第一个解决方案。要在字典中反转键值对,请使用For循环方法:

# Use this code to invert dictionaries that have non-unique values

inverted_dict = dict()
for key, value in my_dict.items():
    inverted_dict.setdefault(value, list()).append(key)

第二个解决方案。使用字典理解方法进行反转:

# Use this code to invert dictionaries that have unique values

inverted_dict = {value: key for key, value in my_dict.items()}

第三个解决方案。使用反转方法(依赖于第二个解决方案):

# Use this code to invert dictionaries that have lists of values

my_dict = {value: key for key in inverted_dict for value in my_map[key]}

列表和字典理解的结合。可以处理重复的密钥

{v:[i for i in d.keys() if d[i] == v ] for k,v in d.items()}

这将处理非惟一值,并保留惟一情况的大部分外观。

inv_map = {v:[k for k in my_map if my_map[k] == v] for v in my_map.itervalues()}

对于Python 3。X,用值替换itervalues。

除了上面建议的其他函数,如果你喜欢lambdas:

invert = lambda mydict: {v:k for k, v in mydict.items()}

或者,你也可以这样做:

invert = lambda mydict: dict( zip(mydict.values(), mydict.keys()) )