comparing dictionaries to find the identical keys

Christian Heimes lists at cheimes.de
Fri Dec 28 08:33:55 EST 2007


Beema shafreen wrote:
> hi everybody ,
> i need to compare two dictionary's key. I have written a script

Use sets. Sets are easier to use and much faster:

>>> d1 = {'a': 1, 'b': 2, 'c': 3}
>>> d2 = {'b': 2, 'c': 3, 'd': 4}
>>> d1.keys()
['a', 'c', 'b']
>>> d2.keys()
['c', 'b', 'd']

>>> s1 = set(d1)
>>> s2 = set(d2)
>>> s1
set(['a', 'c', 'b'])
>>> s2
set(['c', 'b', 'd'])

>>> s1.intersection(s2)
set(['c', 'b'])
>>> s1.union(s2)
set(['a', 'c', 'b', 'd'])
>>> s1.difference(s2)
set(['a'])

Christian




More information about the Python-list mailing list