Equivalence of dictionary keys?

Bengt Richter bokr at oz.net
Tue Dec 2 00:01:15 EST 2003


On Mon, 1 Dec 2003 22:50:04 -0500, "Tim Peters" <tim.one at comcast.net> wrote:

>[Blair Hall]
>> I would like to determine whether two dictionaries have the
>> same set of keys. Can anyone tell me if I HAVE to sort
>> the key sequences as in this code snippet:
>
>Yes, you do.
>
>>     # d1, d2 already created
>>     k1 = d1.keys()
>>     k1.sort()
>>     k2 = d2.keys()
>>     k2.sort()
>>
>>     # are the keys the same?
>>     same = (k1 == k2)
>>
>> I am guessing that two dictionaries with the same keys
>> will sort them in the same order but is this true?
>
>Not necessarily.  The order is an implementation accident, and especially in
>the presence of hash collisions *will* differ between two dicts with the
>same keys if they were inserted in a different order.
>
>If you can afford the memory, a slicker trick is to compare two derived
>dicts with the same keys and known to have equal values.  In 2.3,
>
>    same = dict.fromkeys(d1) == dict.fromkeys(d2)
>
>is enough.  This doesn't sort under the covers, either.  Another trick,
>which should work with any modern Python version:
>
>    if len(d1) == len(d2):
>        temp = d1.copy()
>        temp.update(d2)
>        same = len(temp) == len(d1)
>    else:
>        same = False
>
It is interesting to note that "same keys" means "same" in the sense of ==,
not "same" in the sense some might expect. I.e.,

 >>> class Foo(object):
 ...     def __hash__(self): return 1
 ...     def __cmp__(self,other): return cmp(1, other)
 ...
 >>> foobj = Foo()
 >>> {1:'one'}[foobj]
 'one'
 >>> {1:'a'}.keys()=={1.0:'b'}.keys()=={1L:'c'}.keys()=={True:'d'}.keys()=={foobj:'e'}.keys()
 True

(Skipped the trivial sorts ;-)

Regards,
Bengt Richter




More information about the Python-list mailing list