简体   繁体   中英

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.

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"):

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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