Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two OrderedDict dictionaries?

Tags:

python

How can I compare two OrderedDict dictionareis?

My structure is the following:

dict_a = OrderedDict([(1,4), (2,5), (3,3), (4,5), (5,4), (6,4), (7,4), (8,3), (9,4)])

dict_b = OrderedDict([(1,4), (2,2), (3,1), (4,4), (5,6), (6,7), (7,4), (8,2), (9,5)])

for values in score_dict.items():
if values == course_dict.values():
    print 'match!'
else:
    print 'No match!'

It iterates through and both lists are ordered so it should match on 1 and 7? Thanks in advance!

like image 430
Epalissad Avatar asked Aug 14 '12 21:08

Epalissad


2 Answers

You can use items() and the built-in zip() function:

for i, j in zip(dict_a.items(), dict_b.items()):
    if i == j:
        print(i)

Output:

(1, 4)
(7, 4)
like image 145
Simeon Visser Avatar answered Nov 09 '22 00:11

Simeon Visser


If you want the intersected elements that are the same at each ordered location:

>>> from collections import OrderedDict
>>> dict_a = OrderedDict([(1,4), (2,5), (3,3), (4,5), (5,4), (6,4), (7,4), (8,3), (9,4)])
>>> dict_b = OrderedDict([(1,4), (2,2), (3,1), (4,4), (5,6), (6,7), (7,4), (8,2), (9,5)])
>>> [i1 for i1, i2 in zip(dict_a.iteritems(), dict_b.iteritems()) if i1 == i2]
[(1, 4), (7, 4)]

If you don't care about ordering:

>>> set(dict_a.items()).intersection(set(dict_b.items()))
set([(7, 4), (1, 4)])
like image 37
jterrace Avatar answered Nov 09 '22 00:11

jterrace