在列表字典中合并具有相同值的键

Har*_*Man 1 python dictionary list

我有一个列表字典,并希望在具有重复值的键的情况下只获得一个键.例如:

dic1 = {8: [0, 4], 1: [0, 4], 7:[3], 4:[1, 5], 11:[3]}
Run Code Online (Sandbox Code Playgroud)

结果字典

dic2 = {1: [0, 4], 7:[3], 4:[1, 5]}
Run Code Online (Sandbox Code Playgroud)

策略是反转键中的值,这将变为唯一,然后再次将键反转为各自的值:

dic2 = {y: x for x, y in dic.items()}
Run Code Online (Sandbox Code Playgroud)

但是发生了错误,因为列表不是hashables.如果键具有相同的值,我可以做什么才能获得只有一个键的字典?

Tig*_*kT3 5

将列表转换为可以清除的元组.

dic2 = {tuple(y): x for x, y in dic.items()}
Run Code Online (Sandbox Code Playgroud)

如果您愿意,可以在以后转换回列表:

result = {v:list(k) for k,v in dic2.items()}
Run Code Online (Sandbox Code Playgroud)