简体   繁体   English

比较没有匹配键的两个字典之间的列表值

[英]Comparing list values between two dictionaries that have no matching keys

I have two dictionaries where they keys won't match, but values will. 我有两个字典,它们的键不匹配,但值会匹配。 All values in each dictionary contain 3 list items as ints. 每个字典中的所有值都包含3个以整数表示的列表项。

dict1 = {'red':[1,2,3],'blue':[2,3,4],'orange':[3,4,5]}

dict2 = {'green':[3,4,5],'yellow':[2,3,4],'red':[5,2,6]}

I would like to compare each list and find which two keys have matching value lists. 我想比较每个列表,并找出哪些两个键具有匹配的值列表。 In this case "blue" and "yellow" match, as well as "green" and "orange". 在这种情况下,“蓝色”和“黄色”匹配,以及“绿色”和“橙色”匹配。

I took a look at this thread but was not able to get it to work, and I'm not exactly sure I'm asking the same thing: comparing two dictionaries with list type values 我看了看这个线程,但无法使其正常工作,我不确定是否要问同样的事情: 将两个字典与列表类型值进行比较

I haven't worked with dictionaries before and am not really sure I understand list comprehensions yet, either. 我以前没有和字典一起工作过,也不确定我是否也了解列表理解。 (A lot of posts seem to use them) (很多帖子似乎都在使用它们)

You can use a list comprehension (which is just a shortcut for "for loops"): 您可以使用列表推导(这只是“ for循环”的快捷方式):

matching = [(k1, k2) for k1 in dict1 for k2 in dict2 if dict1[k1] == dict2[k2]]
print matching
# [('blue', 'yellow'), ('orange', 'green')]

Just keep it nice and simple: 只要保持它的美观和简单即可:

dict1 = {'red':[1,2,3],'blue':[2,3,4],'orange':[3,4,5]}

dict2 = {'green':[3,4,5],'yellow':[2,3,4],'red':[5,2,6]}

matches = []
for key1 in dict1:
    for key2 in dict2:
        if dict1[key1] == dict2[key2]:
            matches.append((key1, key2))

print(matches)

Output: 输出:

[('blue', 'yellow'), ('orange', 'green')]

For any case if you don't understand Julien's answer, this doing the same thing. 无论如何,如果您不了解Julien的答案,这都是一样的。

dict1 = {'red':[1,2,3],'blue':[2,3,4],'orange':[3,4,5]}

dict2 = {'green':[3,4,5],'yellow':[2,3,4],'red':[5,2,6]}

for k1,v1 in dict1.items(): #each key and value in dict1
    for k2,v2 in dict2.items(): #each key and value in dict2
        if v1 == v2: #if values match
            print (k1,k2) #print their keys

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM