如何在 Dict 中查找重复值并使用这些值打印键

And*_*dre 1 python dictionary key duplicates

我想知道如何在字典中找到重复的值并返回包含这些值的键。

这是一个例子:

d = {'happy':['sun', 'moon', 'chocolate'], 'sad':['fail', 'test', 'bills'], 'random': ['baloon', 'france', 'sun'] }
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,键的happyrandom具有相同/重复的值,即'sun',所以我正在寻找的输出是:

random, happy
Run Code Online (Sandbox Code Playgroud)

我真的无法理解如何找到这样的重复值。

如果我有一个特定的值,例如“巧克力”,那么我可以简单地使用 d.keys() 进行 for 循环...

Teh*_*ris 5

超级快又脏

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
Run Code Online (Sandbox Code Playgroud)

以定义形式:(你几乎应该总是尝试这样做)

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
Run Code Online (Sandbox Code Playgroud)

那么你可以像这样玩弄这个

 d = {'happy':['sun', 'moon', 'chocolate'], 'sad':['fail', 'test', 'bills'], 'random': ['baloon', 'france', 'sun'] }
 duplicate_dictionary_check(d)
 # or
 duplicate_dictionary_check(d,'sun')
Run Code Online (Sandbox Code Playgroud)