Reputation: 1661
I wanted to know how I can find duplicate values in a dictionary and the return the keys that contain those values.
So here is an example:
d = {'happy':['sun', 'moon', 'chocolate'], 'sad':['fail', 'test', 'bills'], 'random': ['baloon', 'france', 'sun'] }
As you can see the key's happy and random have the same/duplicate value in them, which is 'sun', so the output I was looking for is:
random, happy
I cant really understand how I can find duplicate values like that.
If I had a particular value such as 'Chocolate', then I could simply do a for loop using d.keys() ...
Upvotes: 1
Views: 13731
Reputation: 361
If you're using Python 3 this should output a tuple of any duplicates:
Duplicates = [(i,j) for i in d for j in d if (d[i]==d[j]).all() and i != j]
Upvotes: 0
Reputation: 3217
super quick and dirty
d = {'happy':['sun', 'moon', 'chocolate'], 'sad':['fail', 'test', 'bills'], 'random': ['baloon', 'france', 'sun'] }
specific_word = 'bear' #uncomment to search for specific word
for key_a in d: #loop through the keys of d
for key_b in d: #loop a second time through the keys of d
if key_a == key_b: #if the keys are the same, skip it
break
for item in d[key_a]: #loop through items in d[key_a]
if (item in d[key_b]): #check if the item is in d[key_b]
#if you want to search ONLY for specific_word then this above if statement changes to this:
#if (item in d[key_b]) and item == specific_word:
print key_a,key_b #if u made it this far, print the keys
break # stop printing other stuff, in case of multiple matches
in definition form: ( You should pretty much always try to do it like this)
def duplicate_dictionary_check(d,specific_word=''):
for key_a in d:
for key_b in d
if key_a == key_b:
break
for item in d[key_a]:
if (item in d[key_b]):
if specific_word:
if specific_word == item:
print key_a,key_b,"found specific word:", specific_word
print key_a,key_b,"found match:",item
then you can play around with this like
d = {'happy':['sun', 'moon', 'chocolate'], 'sad':['fail', 'test', 'bills'], 'random': ['baloon', 'france', 'sun'] }
duplicate_dictionary_check(d)
# or
duplicate_dictionary_check(d,'sun')
Upvotes: 5
Reputation: 42788
import collections
d = {'happy':['sun', 'moon', 'chocolate'], 'sad':['fail', 'test', 'bills'], 'random': ['baloon', 'france', 'sun'] }
w = collections.defaultdict(list)
for k,v in d.iteritems():
for i in v: w[i].append(k)
print [l for l in w.itervalues() if len(l)>1]
gives:
[['random', 'happy']]
Upvotes: 1