Python: identifying duplicate values ​​through disparate dictionary keys

here is a dict example

ActivePython 3.1.2.3 (ActiveState Software Inc.) based on
Python 3.1.2 (r312: 79147, Mar 22 2010, 12:20:29) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dict = {}
>>> dict [("127.0.0.1", "127.0.0.2")] = ["value", "value2", "value3"]
>>> dict [("127.0.0.1", "127.0.0.3")] = ["value", "value2", "value3"]
>>> dict [("127.0.0.1", "127.0.0.4")] = ["value1", "value2", "value3"]

Does anyone know of a clean, reliable way to return a list of dictionary keys whose values ​​are identical regardless of the type of value?

in the above example, the first two entries have different keys, but identical values. I am looking for a clean way to get a list of these two keys.

+3
source share
1 answer

Convert a list to a tuple.

As per the example countMapin your post, before you delete it (if it still applies to you):

countMap = {}
for k, v in dict.items():
    v = tuple(v)
    countMap[v] = countMap.get(v,0) + 1

But please do not name your dict variables, as this is a python type name.

Another solution:

index = {}
for k, v in dict.items():
    v = tuple(v)
    index[v] = index.get(v, []) + [k]

Or a cleaner using defaultdict:

from collections import defaultdict

index = defaultdict(list)
for k, v in dict.items():
    index[tuple(v)].append(k)
+3
source

Source: https://habr.com/ru/post/1746256/


All Articles