【发布时间】:2023-03-28 18:25:01
【问题描述】:
是否可以将字典中具有相同值的所有键组合起来,并将键与值交换,将值与键交换?
我不确定这样的事情是否可行,但这是示例。
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']})
【问题讨论】:
标签: python python-2.7