所以我有下面的字典:
adict = {1: set(['a', 'b']), 2: set(['b', 'c'])}
如何反转字典,以便在打印inv_dict时,我得到以下输出:
inv_dict = {'a': set([1]), 'b': set([1, 2]), 'c': set([2])}
答案 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])}