Reputation: 21460
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.
Upvotes: 3
Views: 1220
Reputation: 7349
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)
Upvotes: 3