Comparing value in two dictionaries?

Scott David Daniels Scott.Daniels at Acm.Org
Sat Nov 15 17:56:16 CET 2008


Arnaud Delobelle wrote:
> 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, ...
if you know set(dic1) == set(dic2)  -- that is that the same keys are
used, you could use:
Setup:
     >>> dic1 = dict((c, ord(c)) for c in 'abcdefgh')
     >>> dic2 = dic1.copy()
     >>> dic2['e'] = 12
     >>> dic2['h'] = 13

Comparisons:
     >>> differs = dict((p1[0], (p1[1], p2[1]))
                       for p1, p2 in zip(sorted(dic1.items()),
                                         sorted(dic2.items()))
                       if p1 != p2)

     >>> differs
     {'h': (104, 13), 'e': (101, 12)}


--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list