Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: identifying duplicate values across disparate dictionary keys

here is an example of the dict

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, robust way to return a list of dictionary keys whose values are identical regardless of the value type?

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 those two keys.

like image 887
MadSc13ntist Avatar asked Aug 28 '26 06:08

MadSc13ntist


1 Answers

Convert the list to a tuple.

Based on the example countMap in your post, before you removed it (if it is still relevant to you):

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

But, please don't call your variables dict, since this is the name of a python type.

Other solution:

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

Or cleaner with a defaultdict:

from collections import defaultdict

index = defaultdict(list)
for k, v in dict.items():
    index[tuple(v)].append(k)
like image 121
catchmeifyoutry Avatar answered Aug 30 '26 22:08

catchmeifyoutry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!