如何在Dict中查找重复值并使用这些值打印键 [英] How to find Duplicate values in Dict and print keys with those values
本文介绍了如何在Dict中查找重复值并使用这些值打印键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何在字典中找到重复的值,并返回包含这些值的键.
I wanted to know how I can find duplicate values in a dictionary and the return the keys that contain those values.
所以这是一个例子:
d = {'happy':['sun', 'moon', 'chocolate'], 'sad':['fail', 'test', 'bills'], 'random': ['baloon', 'france', 'sun'] }
您会看到密钥的 happy 和 random 具有相同/重复的值,即'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.
如果我有一个特殊的值,例如'Chocolate',那么我可以简单地使用d.keys()进行for循环...
If I had a particular value such as 'Chocolate', then I could simply do a for loop using d.keys() ...
推荐答案
超级快捷又肮脏
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
然后您就可以像
d = {'happy':['sun', 'moon', 'chocolate'], 'sad':['fail', 'test', 'bills'], 'random': ['baloon', 'france', 'sun'] }
duplicate_dictionary_check(d)
# or
duplicate_dictionary_check(d,'sun')
这篇关于如何在Dict中查找重复值并使用这些值打印键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文