反转/反转字典映射

发布于 2024-07-12 23:34:41 字数 142 浏览 6 评论 0原文

给定一本这样的字典:

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

如何反转该映射以获得:

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

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'}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

扬花落满肩 2024-07-19 23:34:42

字典值是集合的情况。 像:

some_dict = {"1":{"a","b","c"},
        "2":{"d","e","f"},
        "3":{"g","h","i"}}

逆像:

some_dict = {vi: k  for k, v in some_dict.items() for vi in v}

输出是这样的:

{'c': '1',
 'b': '1',
 'a': '1',
 'f': '2',
 'd': '2',
 'e': '2',
 'g': '3',
 'h': '3',
 'i': '3'}

A case where the dictionary values is a set. Like:

some_dict = {"1":{"a","b","c"},
        "2":{"d","e","f"},
        "3":{"g","h","i"}}

The inverse would like:

some_dict = {vi: k  for k, v in some_dict.items() for vi in v}

The output is like this:

{'c': '1',
 'b': '1',
 'a': '1',
 'f': '2',
 'd': '2',
 'e': '2',
 'g': '3',
 'h': '3',
 'i': '3'}
何必那么矫情 2024-07-19 23:34:42

有很多答案,但没有找到任何明确的答案,以防我们谈论具有非唯一值的字典

解决方案是:

from collections import defaultdict

inv_map = defaultdict(list) 
for k, v in my_map.items(): 
    inv_map[v].append(k)

示例:

如果初始字典 my_map = {'c': 1, 'd': 5, 'a': 5, 'b': 10}

那么,运行上面的代码会给:

{5: ['a', 'd'], 1: ['c'], 10: ['b']}

Lot of answers but didn't find anything clean in case we are talking about a dictionary with non-unique values.

A solution would be:

from collections import defaultdict

inv_map = defaultdict(list) 
for k, v in my_map.items(): 
    inv_map[v].append(k)

Example:

If initial dict my_map = {'c': 1, 'd': 5, 'a': 5, 'b': 10}

then, running the code above will give:

{5: ['a', 'd'], 1: ['c'], 10: ['b']}
我三岁 2024-07-19 23:34:42

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

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

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()}
跨年 2024-07-19 23:34:42

我发现这个版本比接受的 10000 个键的字典版本快 10% 以上。

d = {i: str(i) for i in range(10000)}

new_d = dict(zip(d.values(), d.keys()))

I found that this version is more than 10% faster than the accepted version of a dictionary with 10000 keys.

d = {i: str(i) for i in range(10000)}

new_d = dict(zip(d.values(), d.keys()))
半世蒼涼 2024-07-19 23:34:42

除了上面建议的其他函数之外,如果您喜欢 lambda:

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

或者,您也可以这样做:

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

In addition to the other functions suggested above, if you like lambdas:

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

Or, you could do it this way too:

invert = lambda mydict: dict( zip(mydict.values(), mydict.keys()) )
思慕 2024-07-19 23:34:42

我认为最好的方法是定义一个类。 这是“对称字典”的实现:

class SymDict:
    def __init__(self):
        self.aToB = {}
        self.bToA = {}

    def assocAB(self, a, b):
        # Stores and returns a tuple (a,b) of overwritten bindings
        currB = None
        if a in self.aToB: currB = self.bToA[a]
        currA = None
        if b in self.bToA: currA = self.aToB[b]

        self.aToB[a] = b
        self.bToA[b] = a
        return (currA, currB)

    def lookupA(self, a):
        if a in self.aToB:
            return self.aToB[a]
        return None

    def lookupB(self, b):
        if b in self.bToA:
            return self.bToA[b]
        return None

如果需要,删除和迭代方法很容易实现。

这种实现比反转整个字典(这似乎是本页上最流行的解决方案)更有效。 更不用说,您可以根据需要在 SymDict 中添加或删除值,并且您的逆向字典将始终保持有效 - 如果您只是将整个字典逆向一次,则情况并非如此。

I think the best way to do this is to define a class. Here is an implementation of a "symmetric dictionary":

class SymDict:
    def __init__(self):
        self.aToB = {}
        self.bToA = {}

    def assocAB(self, a, b):
        # Stores and returns a tuple (a,b) of overwritten bindings
        currB = None
        if a in self.aToB: currB = self.bToA[a]
        currA = None
        if b in self.bToA: currA = self.aToB[b]

        self.aToB[a] = b
        self.bToA[b] = a
        return (currA, currB)

    def lookupA(self, a):
        if a in self.aToB:
            return self.aToB[a]
        return None

    def lookupB(self, b):
        if b in self.bToA:
            return self.bToA[b]
        return None

Deletion and iteration methods are easy enough to implement if they're needed.

This implementation is way more efficient than inverting an entire dictionary (which seems to be the most popular solution on this page). Not to mention, you can add or remove values from your SymDict as much as you want, and your inverse-dictionary will always stay valid -- this isn't true if you simply reverse the entire dictionary once.

国粹 2024-07-19 23:34:42

如果值不唯一,并且您有点顽固:

inv_map = dict(
    (v, [k for (k, xx) in filter(lambda (key, value): value == v, my_map.items())]) 
    for v in set(my_map.values())
)

特别是对于大型字典,请注意此解决方案的效率远低于答案 Python 反转/反转映射,因为它多次循环 items()

If the values aren't unique, and you're a little hardcore:

inv_map = dict(
    (v, [k for (k, xx) in filter(lambda (key, value): value == v, my_map.items())]) 
    for v in set(my_map.values())
)

Especially for a large dict, note that this solution is far less efficient than the answer Python reverse / invert a mapping because it loops over items() multiple times.

遇到 2024-07-19 23:34:42

这可以处理非唯一值并保留唯一情况的大部分外观。

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

对于 Python 3.x,将 itervalues 替换为 values

This handles non-unique values and retains much of the look of the unique case.

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

For Python 3.x, replace itervalues with values.

一个人的旅程 2024-07-19 23:34:42

我知道这个问题已经有很多好的答案,但我想分享这个非常简洁的解决方案,它还可以处理重复值:

def dict_reverser(d):
    seen = set()
    return {v: k for k, v in d.items() if v not in seen or seen.add(v)}

这依赖于 set.add 始终返回 Python 中没有

I am aware that this question already has many good answers, but I wanted to share this very neat solution that also takes care of duplicate values:

def dict_reverser(d):
    seen = set()
    return {v: k for k, v in d.items() if v not in seen or seen.add(v)}

This relies on the fact that set.add always returns None in Python.

绝情姑娘 2024-07-19 23:34:42

这是另一种方法。

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

inv_map= {}
for key in my_map.keys() :
    val = my_map[key]
    inv_map[val] = key

Here is another way to do it.

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

inv_map= {}
for key in my_map.keys() :
    val = my_map[key]
    inv_map[val] = key
怂人 2024-07-19 23:34:42
dict([(value, key) for key, value in d.items()])
dict([(value, key) for key, value in d.items()])
失与倦" 2024-07-19 23:34:42

函数对于列表类型的值是对称的; 执行reverse_dict(reverse_dict(dictionary))时元组被转换为列表

def reverse_dict(dictionary):
    reverse_dict = {}
    for key, value in dictionary.iteritems():
        if not isinstance(value, (list, tuple)):
            value = [value]
        for val in value:
            reverse_dict[val] = reverse_dict.get(val, [])
            reverse_dict[val].append(key)
    for key, value in reverse_dict.iteritems():
        if len(value) == 1:
            reverse_dict[key] = value[0]
    return reverse_dict

Function is symmetric for values of type list; Tuples are coverted to lists when performing reverse_dict(reverse_dict(dictionary))

def reverse_dict(dictionary):
    reverse_dict = {}
    for key, value in dictionary.iteritems():
        if not isinstance(value, (list, tuple)):
            value = [value]
        for val in value:
            reverse_dict[val] = reverse_dict.get(val, [])
            reverse_dict[val].append(key)
    for key, value in reverse_dict.iteritems():
        if len(value) == 1:
            reverse_dict[key] = value[0]
    return reverse_dict
诗酒趁年少 2024-07-19 23:34:42

由于与值不同,字典在字典中需要一个唯一的键,因此我们必须将反转的值附加到一个排序列表中,以包含在新的特定键中。

def r_maping(dictionary):
    List_z=[]
    Map= {}
    for z, x in dictionary.iteritems(): #iterate through the keys and values
        Map.setdefault(x,List_z).append(z) #Setdefault is the same as dict[key]=default."The method returns the key value available in the dictionary and if given key is not available then it will return provided default value. Afterward, we will append into the default list our new values for the specific key.
    return Map

Since dictionaries require one unique key within the dictionary unlike values, we have to append the reversed values into a list of sort to be included within the new specific keys.

def r_maping(dictionary):
    List_z=[]
    Map= {}
    for z, x in dictionary.iteritems(): #iterate through the keys and values
        Map.setdefault(x,List_z).append(z) #Setdefault is the same as dict[key]=default."The method returns the key value available in the dictionary and if given key is not available then it will return provided default value. Afterward, we will append into the default list our new values for the specific key.
    return Map
同尘 2024-07-19 23:34:42

非双射映射的快速函数解决方案(值不唯一):

from itertools import imap, groupby

def fst(s):
    return s[0]

def snd(s):
    return s[1]

def inverseDict(d):
    """
    input d: a -> b
    output : b -> set(a)
    """
    return {
        v : set(imap(fst, kv_iter))
        for (v, kv_iter) in groupby(
            sorted(d.iteritems(),
                   key=snd),
            key=snd
        )
    }

理论上,这应该比像 势在必行的解决方案

不幸的是,这些值必须是可排序的,groupby 需要排序。

Fast functional solution for non-bijective maps (values not unique):

from itertools import imap, groupby

def fst(s):
    return s[0]

def snd(s):
    return s[1]

def inverseDict(d):
    """
    input d: a -> b
    output : b -> set(a)
    """
    return {
        v : set(imap(fst, kv_iter))
        for (v, kv_iter) in groupby(
            sorted(d.iteritems(),
                   key=snd),
            key=snd
        )
    }

In theory this should be faster than adding to the set (or appending to the list) one by one like in the imperative solution.

Unfortunately the values have to be sortable, the sorting is required by groupby.

喜爱纠缠 2024-07-19 23:34:42

在 python 2.7/3.x 上尝试这个

inv_map={};
for i in my_map:
    inv_map[my_map[i]]=i    
print inv_map

Try this for python 2.7/3.x

inv_map={};
for i in my_map:
    inv_map[my_map[i]]=i    
print inv_map
短叹 2024-07-19 23:34:42
def invertDictionary(d):
    myDict = {}
  for i in d:
     value = d.get(i)
     myDict.setdefault(value,[]).append(i)   
 return myDict
 print invertDictionary({'a':1, 'b':2, 'c':3 , 'd' : 1})

这将提供如下输出:{1: ['a', 'd'], 2: ['b'], 3: ['c']}

def invertDictionary(d):
    myDict = {}
  for i in d:
     value = d.get(i)
     myDict.setdefault(value,[]).append(i)   
 return myDict
 print invertDictionary({'a':1, 'b':2, 'c':3 , 'd' : 1})

This will provide output as : {1: ['a', 'd'], 2: ['b'], 3: ['c']}

谁对谁错谁最难过 2024-07-19 23:34:42

当前 python 3.x 版本的 lambda 解决方案:

d1 = dict(alice='apples', bob='bananas')
d2 = dict(map(lambda key: (d1[key], key), d1.keys()))
print(d2)

结果:

{'apples': 'alice', 'bananas': 'bob'}

此解决方案不检查重复项。

一些备注:

  • lambda 构造可以从外部作用域访问 d1,所以我们只需要
    传入当前密钥。 它返回一个元组。
  • dict() 构造函数接受元组列表。 它
    也接受映射的结果,因此我们可以跳过转换为
    列表。
  • 此解决方案没有显式的 for 循环。 它还避免了对于那些数学不好的人使用列表理解;-)

A lambda solution for current python 3.x versions:

d1 = dict(alice='apples', bob='bananas')
d2 = dict(map(lambda key: (d1[key], key), d1.keys()))
print(d2)

Result:

{'apples': 'alice', 'bananas': 'bob'}

This solution does not check for duplicates.

Some remarks:

  • The lambda construct can access d1 from the outer scope, so we only
    pass in the current key. It returns a tuple.
  • The dict() constructor accepts a list of tuples. It
    also accepts the result of a map, so we can skip the conversion to a
    list.
  • This solution has no explicit for loop. It also avoids using a list comprehension for those who are bad at math ;-)
你与昨日 2024-07-19 23:34:42

如果 my_map 中的值不唯一:开始,我遇到了一个问题,不仅值不是唯一的,但此外,它们是一个列表,列表中的每个项目又由三个元素组成的列表:字符串值、数字和另一个数字。

示例:

mymap['key1'] 为您提供:

[('xyz', 1, 2),
 ('abc', 5, 4)]

我只想用键切换字符串值,将两个数字元素保持在同一位置。 您只需要另一个嵌套的 for 循环即可:

inv_map = {}
for k, v in my_map.items():
    for x in v:
        # with x[1:3] same as x[1], x[2]:
        inv_map[x[0]] = inv_map.get(x[0], []) + [k, x[1:3]]

示例:

inv_map['abc'] 现在为您提供:

[('key1', 1, 2),
 ('key1', 5, 4)]

Taking up the highly voted answer starting If the values in my_map aren't unique:, I had a problem where not only the values were not unique, but in addition, they were a list, with each item in the list consisting again of a list of three elements: a string value, a number, and another number.

Example:

mymap['key1'] gives you:

[('xyz', 1, 2),
 ('abc', 5, 4)]

I wanted to switch only the string value with the key, keeping the two number elements at the same place. You simply need another nested for loop then:

inv_map = {}
for k, v in my_map.items():
    for x in v:
        # with x[1:3] same as x[1], x[2]:
        inv_map[x[0]] = inv_map.get(x[0], []) + [k, x[1:3]]

Example:

inv_map['abc'] now gives you:

[('key1', 1, 2),
 ('key1', 5, 4)]
乞讨 2024-07-19 23:34:42

即使原始字典中有非唯一值,这也有效。

def dict_invert(d):
    '''
    d: dict
    Returns an inverted dictionary 
    '''
    # Your code here
    inv_d = {}
    for k, v in d.items():
        if v not in inv_d.keys():
            inv_d[v] = [k]
        else:
            inv_d[v].append(k)
        inv_d[v].sort()
        print(f"{inv_d[v]} are the values")
        
    return inv_d

This works even if you have non-unique values in the original dictionary.

def dict_invert(d):
    '''
    d: dict
    Returns an inverted dictionary 
    '''
    # Your code here
    inv_d = {}
    for k, v in d.items():
        if v not in inv_d.keys():
            inv_d[v] = [k]
        else:
            inv_d[v].append(k)
        inv_d[v].sort()
        print(f"{inv_d[v]} are the values")
        
    return inv_d
命硬 2024-07-19 23:34:42

根据用例,可能有一种使用枚举的方法:

import enum

class Reverse(enum.Enum):
    a = 1
    b = 2

您可以双向访问值:

Reverse.a       --> prints Reverse.a
Reverse(1)      --> prints Reverse.a

Reverse.a.value --> prints 1
Reverse.a.name  --> prints 'a'

如果开发人员不知道“a”,而是包含在变量中 my_var = 'a',相当于 my_dict[my_var] 是:

getattr(Reverse, my_var) --> prints Reverse.a

Depending on the use case, there is possibly a way to use enum:

import enum

class Reverse(enum.Enum):
    a = 1
    b = 2

You can access the values in both direction:

Reverse.a       --> prints Reverse.a
Reverse(1)      --> prints Reverse.a

Reverse.a.value --> prints 1
Reverse.a.name  --> prints 'a'

If 'a' is not known by the developper but rather contained in a variable my_var = 'a', the equivalent of my_dict[my_var] would be:

getattr(Reverse, my_var) --> prints Reverse.a
扛刀软妹 2024-07-19 23:34:42

我会在 python 2 中这样做。

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

I would do it that way in python 2.

inv_map = {my_map[x] : x for x in my_map}
徒留西风 2024-07-19 23:34:41

Python 3+:

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

Python 2:

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

Python 3+:

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

Python 2:

inv_map = {v: k for k, v in my_map.iteritems()}
GRAY°灰色天空 2024-07-19 23:34:41

假设字典中的值是唯一的:

Python 3:

dict((v, k) for k, v in my_map.items())

Python 2:

dict((v, k) for k, v in my_map.iteritems())

Assuming that the values in the dict are unique:

Python 3:

dict((v, k) for k, v in my_map.items())

Python 2:

dict((v, k) for k, v in my_map.iteritems())
挽袖吟 2024-07-19 23:34:41

如果 my_map 中的值不唯一:

Python 3:

inv_map = {}
for k, v in my_map.items():
    inv_map[v] = inv_map.get(v, []) + [k]

Python 2:

inv_map = {}
for k, v in my_map.iteritems():
    inv_map[v] = inv_map.get(v, []) + [k]

If the values in my_map aren't unique:

Python 3:

inv_map = {}
for k, v in my_map.items():
    inv_map[v] = inv_map.get(v, []) + [k]

Python 2:

inv_map = {}
for k, v in my_map.iteritems():
    inv_map[v] = inv_map.get(v, []) + [k]
独留℉清风醉 2024-07-19 23:34:41

要在保留映射类型的同时执行此操作(假设它是 dictdict 子类):

def inverse_mapping(f):
    return f.__class__(map(reversed, f.items()))

To do this while preserving the type of your mapping (assuming that it is a dict or a dict subclass):

def inverse_mapping(f):
    return f.__class__(map(reversed, f.items()))
暮倦 2024-07-19 23:34:41

试试这个:(

inv_map = dict(zip(my_map.values(), my_map.keys()))

注意字典视图上的Python文档明确保证 .keys().values() 的元素顺序相同,这使得上述方法能够工作。)

或者:

inv_map = dict((my_map[k], k) for k in my_map)

或者使用 python 3.0字典理解

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

Try this:

inv_map = dict(zip(my_map.values(), my_map.keys()))

(Note that the Python docs on dictionary views explicitly guarantee that .keys() and .values() have their elements in the same order, which allows the approach above to work.)

Alternatively:

inv_map = dict((my_map[k], k) for k in my_map)

or using python 3.0's dict comprehensions

inv_map = {my_map[k] : k for k in my_map}
标点 2024-07-19 23:34:41

另一种更实用的方式:

my_map = { 'a': 1, 'b':2 }
dict(map(reversed, my_map.items()))

Another, more functional, way:

my_map = { 'a': 1, 'b':2 }
dict(map(reversed, my_map.items()))
柠檬心 2024-07-19 23:34:41

我们还可以使用 defaultdict 反转具有重复键的字典:

from collections import Counter, defaultdict

def invert_dict(d):
    d_inv = defaultdict(list)
    for k, v in d.items():
        d_inv[v].append(k)
    return d_inv

text = 'aaa bbb ccc ddd aaa bbb ccc aaa' 
c = Counter(text.split()) # Counter({'aaa': 3, 'bbb': 2, 'ccc': 2, 'ddd': 1})
dict(invert_dict(c)) # {1: ['ddd'], 2: ['bbb', 'ccc'], 3: ['aaa']}  

请参阅 此处

此技术比使用 dict.setdefault() 的等效技术更简单、更快。

We can also reverse a dictionary with duplicate keys using defaultdict:

from collections import Counter, defaultdict

def invert_dict(d):
    d_inv = defaultdict(list)
    for k, v in d.items():
        d_inv[v].append(k)
    return d_inv

text = 'aaa bbb ccc ddd aaa bbb ccc aaa' 
c = Counter(text.split()) # Counter({'aaa': 3, 'bbb': 2, 'ccc': 2, 'ddd': 1})
dict(invert_dict(c)) # {1: ['ddd'], 2: ['bbb', 'ccc'], 3: ['aaa']}  

See here:

This technique is simpler and faster than an equivalent technique using dict.setdefault().

一梦等七年七年为一梦 2024-07-19 23:34:41

这扩展了 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

该实现受到限制,因为您不能使用 reversed 两次并恢复原始状态。 它本身并不对称。 它是使用 Python 2.6 进行测试的。 这里是我如何打印结果字典的用例。

如果您更愿意使用 set 而不是 list,并且可能存在对此有意义的无序应用程序,而不是 setdefault(v, []) .append(k),使用setdefault(v, set()).add(k)

This expands upon the answer by Robert, applying to when the values in the dict aren't unique.

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

The implementation is limited in that you cannot use reversed twice and get the original back. It is not symmetric as such. It is tested with Python 2.6. Here is a use case of how I am using to print the resultant dict.

If you'd rather use a set than a list, and there could exist unordered applications for which this makes sense, instead of setdefault(v, []).append(k), use setdefault(v, set()).add(k).

怀念你的温柔 2024-07-19 23:34:41

例如,您有以下字典:

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]}

For instance, you have the following dictionary:

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

And you wanna get it in such an inverted form:

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

First Solution. For inverting key-value pairs in your dictionary use a for-loop approach:

# 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)

Second Solution. Use a dictionary comprehension approach for inversion:

# Use this code to invert dictionaries that have unique values

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

Third Solution. Use reverting the inversion approach (relies on the second solution):

# 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]}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文