Comparing value in two dictionaries?

Arnaud Delobelle arnodel at googlemail.com
Sat Nov 15 13:14:11 EST 2008


Scott David Daniels <Scott.Daniels at Acm.Org> writes:

> 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)}

This may break if two keys are not comparable or if the order on keys is
not total.

Moreover it is O(nlogn) (as sorting is) whereas iterating
over items of one dictionary and looking up the other one will be O(n)
(assuming dictionary lookup is O(1)):

    [k for k, v in dic1.iteritems() if dic2[k] != v]

Or to obtain a dictionary of differences:

    dict((k, (v, dic2[v]) for k, v in dic1.iteritems()
                          if dic2[v] != v)

-- 
Arnaud



More information about the Python-list mailing list