Python删除字典上具有相同值的键 [英] Python remove keys with the same value on a dictionary
问题描述
我需要对字典执行非自然操作,所以我想知道什么是最好的pythonic方法。
I need to do a not "natural" operation on a dictionary so i wondering what is the best pythonic way to do this.
我需要简化字典通过删除所有具有相同值的键(键不同,值相同)
I need to simplify a dictionary by removing all the keys on it with the same value (keys are differents, values are the same)
例如:
输入:
For example: Input:
dict = {key1 : [1,2,3], key2: [1,2,6], key3: [1,2,3]}
预期产量:
{key1 : [1,2,3], key2:[1,2,6]}
我不在乎删除哪个键(例如:key1或key3)
I dont care about which key is delete (on the example: key1 or key3)
推荐答案
交换键和值;重复的键值对将被删除,这是一个副作用(因为字典不允许重复的键)。再次交换键和值。
Exchange keys and values; duplicated key-value pairs will be removed as a side effect (because dictionary does not allow duplicated keys). Exchange keys and values again.
>>> d = {'key1': [1,2,3], 'key2': [1,2,6], 'key3': [1,2,3]}
>>> d2 = {tuple(v): k for k, v in d.items()} # exchange keys, values
>>> d = {v: list(k) for k, v in d2.items()} # exchange again
>>> d
{'key2': [1, 2, 6], 'key1': [1, 2, 3]}
注意:之所以使用 tuple(v)
是因为 list
是不可散列的;不能直接用作键。
NOTE: tuple(v)
was used because list
is not hashable; cannot be used as key directly.
顺便说一句,请勿使用 dict
作为变量名。它将隐藏内置函数/类型 dict
。
BTW, don't use dict
as a variable name. It will shadow builtin function/type dict
.
这篇关于Python删除字典上具有相同值的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!