2014-10-06 35 views
1

我想知道如何在字典中找到重複值並返回包含這些值的鍵。如何在Dict中找到重複值並使用這些值打印鍵值

所以這裏有一個例子:

d = {'happy':['sun', 'moon', 'chocolate'], 'sad':['fail', 'test', 'bills'], 'random': ['baloon', 'france', 'sun'] } 

正如你可以看到關鍵的快樂隨機在他們相同/重複值,這是「太陽」,所以輸出我正在尋找的是:

random, happy 

我真的不明白如何找到這樣的重複值。

如果我有一個特定的值,如「巧克力」,那麼我可以簡單地做一個使用循環運行起來也()...

+0

你想要什麼,輸出是,如果兩對不同的鍵分享不同的詞(例如,如果在你的例子'也sad'包含'moon')? – JB333 2014-10-06 17:44:46

+0

是的,即使2個或2個以上,不同的鍵共享至少1個公共值。然後,那些2(或更多)鍵應該被打印 – Andre 2014-10-06 17:46:31

+0

當然,常用值可以大於1 ..但是至少爲1.然後該函數應該打印那些共享公共值的鍵。 – Andre 2014-10-06 17:47:47

回答

2

超快速和骯髒的

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 

的定義形式:(你應該幾乎總是試圖做這樣的)

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 

那麼你就可以玩這個像

d = {'happy':['sun', 'moon', 'chocolate'], 'sad':['fail', 'test', 'bills'], 'random': ['baloon', 'france', 'sun'] } 
duplicate_dictionary_check(d) 
# or 
duplicate_dictionary_check(d,'sun') 
+0

令人驚歎!在你的答案中很好的解釋! – Andre 2014-10-06 17:50:26

+0

好的,還有一個後續問題:如果你給了一個值「熊」,你會被要求看看'熊'是否作爲字典中的副本存在..如何工作? – Andre 2014-10-06 17:55:43

+0

另外如果有超過2個共同值的鍵。 – Andre 2014-10-06 17:57:26

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

給出:

[['random', 'happy']] 
相關問題