RE: Dict Copy & Compare



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

.



Relevant Pages

  • Re: Some set operators
    ... > methods to dicts), but I've seen that I tend to forget the meaning of ... 1000000 loops, best of 3: 0.929 usec per loop ... for type *int* having the same operators, with bitwise-logic semantics, ...
    (comp.lang.python)
  • Re: Testing for an empty dictionary in Python
    ... object of type 'bool' has no len ... I presume you meant ... is expensive for large dictionaries, ... I don't understand "makes loops O" ... ...
    (comp.lang.python)
  • Coding Nested Loops
    ... I want to code what would be nested "for" loops in C, ... most elegant way of doing the same thing in python. ... one of three strings held in dictionaries, the last 28 fields are random ...
    (comp.lang.python)
  • Re: Testing for an empty dictionary in Python
    ... John Nagle wrote: ... is expensive for large dictionaries, and makes loops O. ... if dict: ...
    (comp.lang.python)