Dict Copy & Compare
mail at timgolden.me.uk
Mon Apr 30 11:14:54 CEST 2007
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.
Couple of points which are confusing me:
1) Any dict can *only* have unique keys, ie you can't have
a key appearing more than once in a dictionary by
2) You speak of unique keys in "this" but unique values
in "that". Is that deliberate on your part? Might be, but
I'm not quite clear.
> I have functions set up for the logging, so I can call it like
> logThis(uniquekey) and logThat(uniquekey).
Here you refer to "uniquekey" in both cases, so maybe a
> 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.
OK, well following by example earlier:
d1 = dict (a=1, b=2, c=3)
d2 = dict (b=4, c=5, d=6)
s1 = set (d1) # => set of 'a', 'b', 'c'
s2 = set (d2) # => set of 'b', 'c', 'd'
s1_not_in_s2 = s1 - s2 # => set of 'a'
s2_not_in_s1 = s2 - s1 # => set of 'd'
for key in s1_not_in_s2:
print key, "=>", d1[key]
for key in s2_not_in_s1:
print key, "=>", d2[key]
Obviously there are more concise ways of representing
this; I'm just spelling the whole thing out to make it
clearer (I hope). If this approach seems fruitful, have
a look at the set typeit's a recentish addition to
Python but very useful for this kind of thing:
More information about the Python-list