Dict Copy & Compare

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Mon Apr 30 06:15:41 EDT 2007


On Mon, 30 Apr 2007 10:05:40 +0100, Robert Rawlins - Think Blue wrote:

> I have two dicts, one named 'this' and the other named 'that'.
> 
> I want to get all the unique keys from 'this' and log them into a file, I
> then want to take all the unique values from 'that' and log them into a
> separate file.


The most straight-forward way is doing a simple pair of loops:

for key in this:
    if key not in that:
        logThis(key)
for key in that:
    if key not in this:
        logThat(key)



> So it's just a case of firstly returning a list of all keys that are in
> 'this' but NOT in 'that' and then visa versa, then loop over them performing
> the function.

Well, if you really do need to collect the list up front (why???) you can
do this:

uniqueFromThis = [key for key in this if key not in that]
uniqueFromThat = [key for key in that if key not in this]


Membership testing in dicts is efficient, so that should run quite fast
unless you have millions of keys common to both dictionaries.



-- 
Steven D'Aprano 




More information about the Python-list mailing list