2014-10-06 60 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']] 
相关问题