Comparing value in two dictionaries?

Arnaud Delobelle arnodel at googlemail.com
Sat Nov 15 09:22:38 EST 2008


Gilles Ganault <nospam at nospam.com> writes:

> Hello
>
> I fill two dictionaries with the same number of keys, and then need to
> compare the value for each key, eg.
>
> #Pour chaque APE, comparaison societe.ape.nombre et verif.ape.nombre
> import apsw
>
> #============
> dic1={}
> [...]
> rows=list(cursor.execute(sql))
> for id in rows:
> 	dic1[id[0]] = id[1]
> #============
> dic2={}
> [...]
> rows=list(cursor.execute(sql))
> for id in rows:
> 	dic2[id[0]] = id[1]
> #============
> #Here, compare each key/value to find values that differ
> for i in dic1.items():
> 	[...]
> 		
> What would be a good way to do this in Python?
>
> Thank you.

I think you would be better off writing some SQL query that does it.

If you want to do this in Python, I suppose it depends whether you know
that the two dictionaries have the same set of keys.  If they do you can
simply write something like:

diff = [key for key, val1 in dic1.iteritems() if val1 != dic2[key]]

-- 
Arnaud



More information about the Python-list mailing list