使用字典中的值交换键的改进?

时间:2012-11-20 07:27:27

标签: python dictionary

我在字典中读到了两个关于交换键的问题:Python: Best Way to Exchange Keys with Values in a Dictionary?; How to swap keys for values in a dictionary?

推广的最佳方法是:

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

但是,如果是这样的字典:

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

mothed获取交换字典:

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

项目(1:'a')迷路了。那么如何才能得到像这样的字典{1:('one','a'),2:'two'}?感谢。

4 个答案:

答案 0 :(得分:4)

这是一种方法:

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

如果你真的想要一个单行(我强烈建议不要这样做 - 效率非常低):

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

希望这有帮助

答案 1 :(得分:4)

您可以使用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']}

或者您也可以使用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']})

答案 2 :(得分:2)

d = {"one":1, "two":2, "a":1}
a = {}
for k,v in d.iteritems():
    a.setdefault(v, []).append(k)

如果必须是单行:

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

答案 3 :(得分:0)

我不确定是否有一个班轮,但这有效:

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

for key, val in old.iteritems():
    new[val] = new.get(val, []) + [key]