473,386 Members | 1,830 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Equivalence of dictionary keys?

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?

Jul 18 '05 #1
3 1682
On Tue, Dec 02, 2003 at 04:22:52PM +1300, Blair Hall wrote:
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?


Not necessarily. There's at least one case where this isn't true: in the
case of hash collisions between keys inserted in different orders in the two
dictionaries, e.g.:
class C: .... def __hash__(self):
.... return 1
.... c1, c2 = C(), C()
d1, d2 = {}, {}
d1[c1] = 'a'
d1[c2] = 'b'
d2[c2] = 'b'
d2[c1] = 'a'
d1.keys() [<__main__.C instance at 0x4021b7ec>, <__main__.C instance at 0x4021b5ec>] d2.keys() [<__main__.C instance at 0x4021b5ec>, <__main__.C instance at 0x4021b7ec>]
In pathological cases, even sorting the keys isn't enough:
class C: .... def __hash__(self):
.... return 1
.... def __eq__(self, other):
.... return 0
.... def __lt__(self, other):
.... return 1
.... c1, c2 = C(), C()
d1, d2 = {}, {}
d1[c1] = 'a'
d1[c2] = 'b'
d2[c2] = 'b'
d2[c1] = 'a'
k1 = d1.keys()
k2 = d2.keys()
k1 [<__main__.C instance at 0x4021b54c>, <__main__.C instance at 0x4021b5cc>] k2 [<__main__.C instance at 0x4021b5cc>, <__main__.C instance at 0x4021b54c>] k1.sort()
k2.sort()
k1 == k2 False k1 [<__main__.C instance at 0x4021b5cc>, <__main__.C instance at 0x4021b54c>] k2 [<__main__.C instance at 0x4021b54c>, <__main__.C instance at 0x4021b5cc>]


-Andrew.
Jul 18 '05 #2
Blair Hall <b.****@irl.cri.nz> wrote in news:3F**************@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 du****@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?
Jul 18 '05 #3
Duncan Booth:
Blair Hall:
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:


Borrowing your jumble keys example, you can also use sets

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

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

a = d.keys()
b = c.keys()

import sets
print sets.Set(a) == sets.Set(b)

--

Emile van Sebille
em***@fenx.com

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: none | last post by:
or is it just me? I am having a problem with using a dictionary as an attribute of a class. This happens in python 1.5.2 and 2.2.2 which I am accessing through pythonwin builds 150 and 148...
57
by: Egor Bolonev | last post by:
why functions created with lambda forms cannot contain statements? how to get unnamed function with statements?
41
by: Xah Lee | last post by:
here's another interesting algorithmic exercise, again from part of a larger program in the previous series. Here's the original Perl documentation: =pod merge($pairings) takes a list of...
5
by: Rakesh | last post by:
Hi, For a particular problem of mine, I want to sort <key, value> pairs by its value. Eg: Input: A, 4 B, 5
4
by: Noah | last post by:
I have a dictionary that I would like to expand to satisfy a function's agument list. I can used the ** syntax to pass a dictionary, but this only works if each key in the dictionary matches an...
90
by: Christoph Zwerschke | last post by:
Ok, the answer is easy: For historical reasons - built-in sets exist only since Python 2.4. Anyway, I was thinking about whether it would be possible and desirable to change the old behavior in...
14
by: vatamane | last post by:
This has been bothering me for a while. Just want to find out if it just me or perhaps others have thought of this too: Why shouldn't the keyset of a dictionary be represented as a set instead of a...
11
by: John | last post by:
I am coding a radix sort in python and I think that Python's dictionary may be a choice for bucket. The only problem is that dictionary is a mapping without order. But I just found that if the...
8
by: Bob Altman | last post by:
Hi all, I'm trying to do something that should be really easy, but I can't think of an obvious way to do it. I have a dictionary whose value is a "value type" (as opposed to a reference type --...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.