Reputation: 418
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)
Upvotes: 0
Views: 2227
Reputation: 26315
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')]
Upvotes: 1
Reputation: 15423
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')]
Upvotes: 1
Reputation: 4035
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
Upvotes: -1