How to find Duplicate values in Dict and print keys with those values

倖福魔咒の 提交于 2021-01-28 06:20:28

问题


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() ...


回答1:


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')



回答2:


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']]



回答3:


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]


来源:https://stackoverflow.com/questions/26221692/how-to-find-duplicate-values-in-dict-and-print-keys-with-those-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!