3

I've read two questions about exchange keys with values in a dictionary: Python: Best Way to Exchange Keys with Values in a Dictionary?; How to swap keys for values in a dictionary?.

The best mothod promoted is:

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

However, if a dictionary like this:

d = {"one":1, "two":2, "a":1}

the mothed gets the swapped dictionary:

{1: 'one', 2: 'two'}

The item (1:'a') gets lost. So how can I get a dictionary like this {1: ('one', 'a'), 2: 'two'}? Thanks.

Community
  • 1
  • 1
zfz
  • 1,597
  • 1
  • 22
  • 45

4 Answers4

4

Here's one way of doing it:

In [101]: d = {"one":1, "two":2, "a":1}

In [102]: answer = collections.defaultdict(list)

In [103]: for k,v in d.iteritems():
   .....:     answer[v].append(k)

   .....:     

In [104]: answer
Out[104]: defaultdict(<type 'list'>, {1: ['a', 'one'], 2: ['two']})

In [105]: dict(answer)
Out[105]: {1: ['a', 'one'], 2: ['two']}

In [106]: dict((k, tuple(v)) for k,v in answer.iteritems())
Out[106]: {1: ('a', 'one'), 2: ('two',)}

If you really want a one-liner (I highly recommend against this - it's very inefficient):

In [110]: d
Out[110]: {'a': 1, 'one': 1, 'two': 2}

In [111]: dict((v, tuple([key for key in d if d[key]==v])) for k,v in d.iteritems())
Out[111]: {1: ('a', 'one'), 2: ('two',)}

Hope this helps

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
4

you can use dict.setdefault():

In [6]: dd={}

In [7]: for x,y in d.items():
   ...:     dd.setdefault(y,[]).append(x)
   ...:     

In [8]: dd
Out[8]: {1: ['a', 'one'], 2: ['two']}

or you can also use defaultdict():

In [1]: from collections import defaultdict

In [2]: d = {"one":1, "two":2, "a":1}

In [3]: dd=defaultdict(list)

In [4]: for x,y in d.items():
   ...:     dd[y].append(x)
   ...:     

In [5]: dd
Out[5]: defaultdict(<type 'list'>, {1: ['a', 'one'], 2: ['two']})
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
2
d = {"one":1, "two":2, "a":1}
a = {}
for k,v in d.iteritems():
    a.setdefault(v, []).append(k)

If it has to be a one-liner:

import itertools as it
import operator as op

a = {k:tuple(b[0] for b in v) for k,v in it.groupby(sorted(d.items(), key=op.itemgetter(1)), key=op.itemgetter(1))}
eumiro
  • 207,213
  • 34
  • 299
  • 261
0

I'm not sure of a one liner, but this works:

old = {"one": 1, "two": 2, "a": 1}
new = {}

for key, val in old.iteritems():
    new[val] = new.get(val, []) + [key]
Tim
  • 11,710
  • 4
  • 42
  • 43