组合字典中具有相同值的所有键,然后将键与值交换,并将值与键交换

时间:2019-07-30 05:01:26

标签: python python-2.7

是否可以将字典中具有相同值的所有键组合在一起,并用值和键值交换键?

我不确定是否还可以进行类似的操作,但这是示例。

mydict = {'./three/failures/1.log': ['UVM_ERROR: This is one error'], './one/failures/1.log': ['UVM_ERROR: This is one error'], './two/failures/1.log': ['UVM_ERROR: This is two error']}

预期输出:

{'UVM_ERROR: This is one error': ['./three/failures/1.log', ./one/failures/1.log'], 'UVM_ERROR: This is two error': ['./two/failures/1.log']}

我发现找到具有相同值的键的小提示:

>>> [k for k,v in a.items() if v == 'UVM_ERROR: This is one error']
['./one/failures/1.log', './three/failures/1.log']

尝试其中一种解决方案后更新: 如果我的字典中的任何键都不具有相同的值,则defaultdict不起作用。

例如:

Dictionary :  {'./three/failures/1.log': 'UVM_ERROR: This is three error', './one/failures/1.log': 'UVM_ERROR: This is one error', './two/failures/1.log': 'UVM_ERROR: This is two error'}

输出:

defaultdict(<type 'list'>, {'U': ['./three/failures/1.log', './one/failures/1.log', './two/failures/1.log']})

3 个答案:

答案 0 :(得分:1)

您可以使用defaultdict

from collections import defaultdict

mydict = {'./three/failures/1.log': 'UVM_ERROR: This is one error', './one/failures/1.log': 'UVM_ERROR: This is one error', './two/failures/1.log': 'UVM_ERROR: This is two error'}

output = defaultdict(list)

for k, v in mydict.items():
    output[v].append(k)

print output

输出:

defaultdict(<type 'list'>, {'UVM_ERROR: This is two error': ['./two/failures/1.log'], 'UVM_ERROR: This is one error':['./three/failures/1.log', './one/failures/1.log']})

defaultdict源自dict,因此您可以像使用dict一样精确地使用它。如果您真的想要纯dict,只需dict(output)

答案 1 :(得分:1)

您可以使用itertools.groupby按值(doc)将mydict项分组:

mydict = {'./three/failures/1.log': ['UVM_ERROR: This is one error'], './one/failures/1.log': ['UVM_ERROR: This is one error'], './two/failures/1.log': ['UVM_ERROR: This is two error']}

from itertools import groupby

out = {}
for v, g in groupby(sorted(mydict.items(), key=lambda k: k[1]), lambda k: k[1]):
    out[v[0]] = [i[0] for i in g]

print(out)

打印:

{'UVM_ERROR: This is one error': ['./three/failures/1.log', './one/failures/1.log'],
 'UVM_ERROR: This is two error': ['./two/failures/1.log']}

答案 2 :(得分:0)

这不太困难。实际上,您可以在线完成所有操作!

d = {'a':1, 'b':2}
d0 = dict(zip(list(d.values()), list(d.keys())))
d0
{1: 'a', 2: 'b'}