Equivalence of dictionary keys?

Tim Peters tim.one at comcast.net
Mon Dec 1 22:50:04 EST 2003


[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






More information about the Python-list mailing list