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

2024-09-22 16:34:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

下面是一个例子:

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

如您所见,键的happyrandom具有相同/重复的值,即“sun”,因此我要的输出是:

random, happy

我真的不明白我怎么能找到那样的重复值。

如果我有一个特定的值,比如“Chocolate”,那么我可以使用d.keys()简单地执行for循环。。。


Tags: test字典randomkeys例子failsunhappy
3条回答

如果您使用的是Python 3,那么应该输出一个包含任何重复项的元组:

Duplicates = [(i,j) for i in d for j in d if (d[i]==d[j]).all() and i != j]
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']]

超快速和肮脏

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

相关问题 更多 >