1017

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'}
smci
  • 32,567
  • 20
  • 113
  • 146
Brian M. Hunt
  • 81,008
  • 74
  • 230
  • 343

33 Answers33

1439

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()}
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
225

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())
questionto42
  • 7,175
  • 4
  • 57
  • 90
  • 27
    The values have to be hashable too – John La Rooy May 24 '12 at 01:52
  • 35
    @Buttons840: If the values aren’t unique, there is no unique inversion of the dictionary anyway or, with other words, inverting does not make sense. – Wrzlprmft Oct 25 '14 at 14:13
  • 2
    @Buttons840 Only the last key will appear for the value. There are probably no guarantees on the order that `iteritems()` will output, so it may be assumed that an arbitrary key will be assigned for a non-unique value, in a way that will be apparently reproducible under some conditions, but no so in general. – Evgeni Sergeev Apr 21 '15 at 08:13
  • 2
    Note, of course, that in Python 3 there is no longer an `iteritems()` method and this approach will not work; use `items()` there instead as shown in the accepted answer. Also, a dictionary comprehension would make this prettier than calling `dict`. – Mark Amery Jul 16 '16 at 17:17
  • 7
    @Wrzlprmft There is a natural definition for inverse in the case of non unique values. Every value is mapped to the set of keys leading to it. – Leo Oct 25 '16 at 19:08
194

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]
questionto42
  • 7,175
  • 4
  • 57
  • 90
Robert Rossney
  • 94,622
  • 24
  • 146
  • 218
  • 69
    ... or just inv_map.setdefault(v, []).append(k). I used to be a defaultdict fanboy, but then I got screwed one too many times and concluded that actually explicit is better than implicit. – alsuren Nov 10 '10 at 14:55
  • This answer is incorrect for multi-map, append here is useless because the value is reset to empty list each time, should use set_default – Yaroslav Bulatov Apr 22 '16 at 20:37
  • 2
    @YaroslavBulatov no, the code as shown here isn't broken - `inv_map.get(v, [])` returns the already-added list if there is one, so the assignment doesn't reset to an empty list. `setdefault` would still be prettier, though. – Mark Amery Jul 16 '16 at 17:23
  • 15
    A set would make more sense here. The keys are (probably) hashable, and there is no order. `inv_map.setdefault(v, set()).add(k)`. – Artyer Aug 11 '17 at 17:17
  • 5
    In python3, use `my_map.items()` instead of `my_map.iteritems()`. – apitsch Apr 15 '19 at 15:02
  • 1
    You can avoid `setdefault` by using a `defaultdict`: `inv_map = collections.defaultdict(set)` and then simply `inv_map[v].add(k)` – Conchylicultor Jan 29 '20 at 22:45
  • Isn't it evaluating the expression `[]` and creating an empty list in every iteration? – Carlos Roldán Mar 18 '21 at 17:48
  • This answer helped me the most since I could tweak it much easier for a more complicated problem with [non-unique items and a nested list in the value where only the first inner list elements should be switched with the key](https://stackoverflow.com/a/70456310/11154841). – questionto42 Dec 23 '21 at 00:04
  • 1
    @JuanC.Roldán it is, but it isn't a big deal. – juanpa.arrivillaga Jun 28 '22 at 10:15
53

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()))
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
fs.
  • 898
  • 6
  • 8
  • 4
    Clever it may be, but it doesn't work when more than one key has the same value in the original dictionary. – Rafael_Espericueta Jun 05 '18 at 01:02
  • 9
    @Rafael_Espericueta That's true of any possible answer to this question, since a map with values repeated is not invertible. – Mark Amery Jul 15 '19 at 01:56
  • 2
    @Mark_Amery It can be invertible more generally, in a sense. For example: D = {1: [1, 2], 2:[2, 3], 3: [1]}, Dinv = {1: [1, 3], 2: [1, 2], 3: [2]}. D is a dictionary of for example {parent: children}, while Dinv is the dictionary {child: parents}. – Rafael_Espericueta Jul 21 '19 at 23:48
  • 3
    I don't think it is necessary to do the `f.__class__` because you already made the assumption that it is a dictionary. I would do it like this: `dict(map(reversed, f.items()))` – bkbilly Jul 05 '20 at 15:34
  • @bkbilly no assumption was made we have a dict - only we have an `items` method – Mr_and_Mrs_D Apr 27 '21 at 09:00
48

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}
Rick
  • 43,029
  • 15
  • 76
  • 119
sykora
  • 96,888
  • 11
  • 64
  • 71
  • 2
    Notice that this only works if the keys are unique (which is almost never the case if you want to invert them). – gented Jun 22 '18 at 08:26
  • According to https://www.python.org/dev/peps/pep-0274/ dict comprehensions are available in 2.7+, too. – Kawu Oct 27 '18 at 01:03
42

Another, more functional, way:

my_map = { 'a': 1, 'b':2 }
dict(map(reversed, my_map.items()))
Brendan Maguire
  • 4,188
  • 4
  • 24
  • 28
  • 4
    Thanks for posting. I am not sure this is preferable - to quote Guido Van Rossum in PEP 279: "`filter` and `map` should die and be subsumed into list comprehensions, not grow more variants". – Brian M. Hunt Feb 26 '14 at 16:38
  • 2
    Yeah, that's a fair point Brian. I was just adding it as a point of conversation. The dict comprehension way is more readable for most I'd imagine. (And likely faster too I'd guess) – Brendan Maguire Feb 26 '14 at 17:10
  • 3
    Might be less readable than others, but this way does have the benefit of being able to swap out `dict` with other mapping types such as `collections.OrderedDict` or `collections.defaultdict` – Will S Aug 17 '17 at 09:51
19

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().

irudyak
  • 2,271
  • 25
  • 20
  • It can be good to return `dict(d_inv)`, since a dictionary has broader support than a less standard `defaultdict`. For example, some serializers (such as `yaml.safe_dump`) won't serialize a `defaultdict` while they will serialize a `dict`. – Konstantin Dec 22 '20 at 16:09
16

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

Asclepius
  • 57,944
  • 17
  • 167
  • 143
  • this would also be a good place to use sets instead of lists, i.e. `revdict.setdefault(v, set()).add(k)` – mueslo Dec 22 '16 at 20:42
  • Of course, but that's exacty why it's a good reason to use `set`. It's the intrinsic type that applies here. What if I want to find all keys where the values are not `1` or `2`? Then I can just do `d.keys() - inv_d[1] - inv_d[2]` (in Python 3) – mueslo Dec 22 '16 at 20:57
11

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'}
Mondaa
  • 127
  • 3
  • 4
10

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()}
SVJ
  • 125
  • 1
  • 4
  • 3
    Like https://stackoverflow.com/a/41861007/1709587, this is an O(n²) solution to a problem that is easily solved in O(n) with a couple of extra lines of code. – Mark Amery Jul 15 '19 at 02:31
10

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]}
Paul Wintz
  • 2,542
  • 1
  • 19
  • 33
Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
10

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']}
Ani Menon
  • 27,209
  • 16
  • 105
  • 126
3

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()))
nauer
  • 690
  • 5
  • 14
2

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()) )
RussellStewart
  • 5,293
  • 3
  • 26
  • 23
  • 2
    -1; all you've done is taken other answers from the page and put them into a lambda. Also, assigning a lambda to a variable is a [PEP 8](https://www.python.org/dev/peps/pep-0008) violation. – Mark Amery Jul 16 '16 at 18:03
2

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.

NcAdams
  • 2,521
  • 4
  • 21
  • 32
  • I like this idea, though it would be good to note that it trades off additional memory to achieve improved computation. A happier medium may be caching or lazily computing the mirror. It is also worth noting that it could be made more syntactically appealing with e.g. dictionary views and custom operators. – Brian M. Hunt Sep 28 '14 at 10:59
  • @BrianM.Hunt It trades off memory, but not a lot. You only store two sets of pointers to each object. If your objects are much bigger than single integers, this won't make much of a difference. If you have huge table of tiny objects on the other hand, you might need to consider those suggestions... – NcAdams Sep 28 '14 at 20:46
  • And I agree, there's more to be done here -- I might flesh this out into a fully functioning datatype later – NcAdams Sep 28 '14 at 20:47
  • 2
    *"This implementation is way more efficient than inverting an entire dictionary"* - um, why? I don't see any plausible way this approach can have a significant performance benefit; you've still got two dictionaries this way. If anything, I'd expect this to be *slower* than, say, inverting the dict with a comprehension, because if you invert the dict Python can plausibly know in advance how many buckets to allocate in the underlying C data structure and create the inverse map without ever calling `dictresize`, but this approach denies Python that possibility. – Mark Amery Jul 16 '16 at 18:11
2

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.

Community
  • 1
  • 1
pcv
  • 2,121
  • 21
  • 25
  • 9
    This is just plain unreadable and a good example of how to not write maintainable code. I won't `-1` because it still answers the question, just my opinion. – Russ Bradberry Oct 03 '12 at 19:19
2

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.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • 4
    This solution is quite elegant as a one liner and it manages the non unique values case. However it has a complexity in O(n2) which means it should be ok for several dozens of elements but it would be too slow for practical use if you have several hundreds of thousands of elements in your initial dictionary. The solutions based on a default dict are way faster than this one. – gabuzo Oct 24 '17 at 08:21
  • Gabuzo is quite right. This version is (arguably) clearer than some, but it is not suitable for large data. – Ersatz Kwisatz Oct 25 '17 at 17:01
2

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.

mss
  • 195
  • 1
  • 8
1

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
1
dict([(value, key) for key, value in d.items()])
algorytmus
  • 953
  • 2
  • 9
  • 28
1

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
user42
  • 871
  • 1
  • 10
  • 28
0

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.

Community
  • 1
  • 1
cjay
  • 25
  • 2
  • 1
    *"In theory this should be faster than adding to the set (or appending to the list) one by one"* - no. Given `n` elements in the original dict, your approach has `O(n log n)` time complexity due to the need to sort the dict's items, whereas the naive imperative approach has `O(n)` time complexity. For all I know your approach may be faster up until absurdly large `dict`s in *practice*, but it certainly isn't faster in theory. – Mark Amery Jul 16 '16 at 18:17
0

Try this for python 2.7/3.x

inv_map={};
for i in my_map:
    inv_map[my_map[i]]=i    
print inv_map
Rick
  • 43,029
  • 15
  • 76
  • 119
dhvlnyk
  • 197
  • 2
  • 15
0

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
Alf
  • 9
  • 3
0

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
eyoeldefare
  • 2,136
  • 1
  • 15
  • 25
0
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']}

RVR
  • 651
  • 2
  • 6
  • 14
  • Iterating key-value pairs simultaneously via `dict.items` (or `iteritems` in Python 2) is more efficient than extracting each value separately while iterating keys. Also, you have added no explanation to an answer which duplicates others. – jpp Aug 25 '19 at 08:37
0

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 ;-)
mit
  • 11,083
  • 11
  • 50
  • 74
  • I could not find this solution using google search or in the other answers or in the dupliate questions, so I created it. – mit Jun 16 '20 at 15:15
0

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)]
questionto42
  • 7,175
  • 4
  • 57
  • 90
0

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
-1

I would do it that way in python 2.

inv_map = {my_map[x] : x for x in my_map}
Cedar
  • 748
  • 6
  • 21
  • Iterating key-value pairs simultaneously via `dict.items` (or `iteritems` in Python 2) is more efficient than extracting each value separately while iterating keys. – jpp Aug 23 '19 at 14:38
-2

Not something completely different, just a bit rewritten recipe from Cookbook. It's futhermore optimized by retaining setdefault method, instead of each time getting it through the instance:

def inverse(mapping):
    '''
    A function to inverse mapping, collecting keys with simillar values
    in list. Careful to retain original type and to be fast.
    >> d = dict(a=1, b=2, c=1, d=3, e=2, f=1, g=5, h=2)
    >> inverse(d)
    {1: ['f', 'c', 'a'], 2: ['h', 'b', 'e'], 3: ['d'], 5: ['g']}
    '''
    res = {}
    setdef = res.setdefault
    for key, value in mapping.items():
        setdef(value, []).append(key)
    return res if mapping.__class__==dict else mapping.__class__(res)

Designed to be run under CPython 3.x, for 2.x replace mapping.items() with mapping.iteritems()

On my machine runs a bit faster, than other examples here

thodnev
  • 1,564
  • 16
  • 20
  • 1
    Building the result as a `dict` and then converting to the desired class at the end (rather than starting with a class of the right type) looks to me like it incurs an entirely avoidable performance hit, here. – Mark Amery Jul 15 '19 at 02:09
-2

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
-2

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)
mveith
  • 1
  • 3
  • You might improve your solutions using a defaultdict: it'll remove all the invDict[item] = invDict.get(item, []) lines – gabuzo Oct 24 '17 at 08:22
  • Your first approach here converts `{"foo": "bar"}` to `{'b': ['foo'], 'a': ['foo'], 'r': ['foo']}` and raises an exception if any value in `myDict` is not an iterable. I'm not sure what behaviour you were trying to implement here, but what you've actually implemented is something pretty much nobody is going to want. – Mark Amery Jul 15 '19 at 02:25