如何对设置为值的字典进行反向排序?

时间:2015-12-17 21:46:03

标签: python dictionary data-structures set

所以我有下面的字典:

adict = {1: set(['a', 'b']), 2: set(['b', 'c'])}

如何反转字典,以便在打印inv_dict时,我得到以下输出:

inv_dict = {'a': set([1]), 'b': set([1, 2]), 'c': set([2])}

1 个答案:

答案 0 :(得分:3)

在字典上循环,构建一个新的:

inverse = {}
for key, values in adict.items():
    for value in values:
        inverse.setdefault(value, set()).add(key)

演示:

>>> adict = {1: set(['a', 'b']), 2: set(['b', 'c'])}
>>> inverse = {}
>>> for key, values in adict.items():
...     for value in values:
...         inverse.setdefault(value, set()).add(key)
...
>>> inverse
{'a': set([1]), 'c': set([2]), 'b': set([1, 2])}