Equivalence of dictionary keys?

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Dec 2 04:22:49 EST 2003


Blair Hall <b.hall at irl.cri.nz> wrote in news:3FCC058C.6070205 at irl.cri.nz:

> 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:
> 
>     # 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?

Here's a simple counter-example using not two but one dictionary. Just 
manipulating a dictionary can change the order of the keys:

>>> d = {'a':1, 'b': 2, 'c': 3}
>>> d.keys()
['a', 'c', 'b']
>>> for i in range(100):
        d[i] = i

	
>>> for i in range(100):
        del d[i]

	
>>> d.keys()
['c', 'b', 'a']
>>> 

However, the answer to your original question is NO, you don't have to sort 
the keys to find out whether the two dictionaries are the same. You could 
just iterate over one set of keys and check for membership of the other 
set.

def samekeys(d1, d2):
    if len(d1) != len(d2):
        return False
    for k in d1:
        if not k in d2:
            return False
    return True

dict1 = {'a':1, 'b': 2, 'c': 3}
dict2 = dict1.copy()
for i in range(100):
    dict1[i] = i
for i in range(100):
    del dict1[i]

print dict1.keys()
print dict2.keys()
print samekeys(dict1, dict2)

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list