Strategy for determing difference between 2 very large dictionaries

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Dec 24 04:10:16 EST 2008


En Wed, 24 Dec 2008 06:23:00 -0200, <python at bdurham.com> escribió:

> Hi Gabriel,
>
> Thank you very much for your feedback!
>
>> k1 = set(dict1.iterkeys())
>
> I noticed you suggested .iterkeys() vs. .keys(). Is there any advantage
> to using an iterator vs. a list as the basis for creating a set? I

You've got an excelent explanation from Marc Rintsch. (Note that in Python  
3.0 keys() behaves as iterkeys() in previous versions, so the above code  
is supposed to be written in Python 2.x)

>>> can this last step be done via a simple list comprehension?
>
>> Yes; but isn't a dict comprehension more adequate?
>>
>> [key: (dict1[key], dict2[key]) for key in common_keys if
>> dict1[key]!=dict2[key]}
>
> Cool!! I'm relatively new to Python and totally missed the ability to
> work with dictionary comprehensions. Yes, your dictionary comprehension
> technique is much better than the list comprehension approach I was
> struggling with. Your dictionary comprehension statement describes
> exactly what I wanted to write.

This time, note that dict comprehensions require Python 3.0 -- so the code  
above won't work in Python 2.x.
(It's not a good idea to mix both versions in the same post, sorry!)
You might use instead:

dict((key,(dict1[key],dict2[key])) for key in ...)

but it's not as readable.

-- 
Gabriel Genellina




More information about the Python-list mailing list