comparing dictionaries

Arnaud Delobelle arnodel at googlemail.com
Wed May 7 14:09:08 EDT 2008


brad <byte8bits at gmail.com> writes:

> I want to compare two dicts that should have identical info just in a
> different data structure. The first dict's contents look like this. It
> is authoritative... I know for sure it has the correct key value
> pairs:
>
> {'001' : '01'}

-> refdict

>
> The second dict's contents are like this with a tuple instead of a
> string for the key:
>
> {('This is one', '001'): '01'}

-> multidict

>
> Pseudo Code:
> for key, value in first_dict.iteritems():
>   # How do I do the following line?
>   if key not in second_dict or if it is, but has has the wrong value,
> then let me know

I think it's best to iterate over items of the second dictionary
first.  I am assuming that a key can be repeated in the second
dictionary, otherwise it could be a bit simpler:

missing_keys = set(first_dict)
for keys, val in second_dict.iteritems():
    for key in keys:
        missing_keys.discard(key)
        if first_dict.get(key, val) != val:
            print "wrong value for", key, 'in', keys
if missing_keys:
    print 'some keys are missing:', ',',join(remaining) 

-- 
Arnaud



More information about the Python-list mailing list