dictionary comparison

Olivier Dagenais olivierS.dagenaisP at canadaA.comM
Thu Aug 10 12:12:16 EDT 2000


I solved this problem yesterday!  (or very early this morning..)

In order to avoid a O(n^2) comparison, you can do something like:  (this is
O(n), since dictionaries are implemented using hash tables)

for key1 in dict1.keys ( ):
    if ( dict2.has_key ( key1 ) ):
        dict2.remove ( key1 )
    else:
        # dict2 is missing entry with key1, hence the dictionaries are
different

if there are any elements left in dict2 after this loop, dict2 contained
elements that weren't in dict1, hence they are different...

Of course, this only checks if the same keys are present in both
dictionaries..  (you may want to make a copy of dict2, also!)  But after
this check, you can do this one:  (again O(n))

for key1 in dict1.keys ( ):
    if ( dict1[key1] != dict2[key1] ):
        # the dictionaries are different

I hope I answered your question to your satisfaction...

--
----------------------------------------------------------------------
Olivier A. Dagenais - Carleton University - Computer Science III


<pzs at dcs.gla.ac.uk> wrote in message news:8muih7$om6$1 at nnrp1.deja.com...
> I know this is going to be newbie-type question, so I apologise in
> advance.
>
> What's the best way of comparing a dictionary with another (possibly
> itself) without doing each comparison twice as
>
> for key1 in dict1.keys():
> for key2 in dict2.keys():
>
> would?
>
> Peter
>
>
> Sent via Deja.com http://www.deja.com/
> Before you buy.





More information about the Python-list mailing list