Dict Copy & Compare

Robert Rawlins - Think Blue robert.rawlins at thinkbluemedia.co.uk
Mon Apr 30 11:05:40 CEST 2007

Thanks for that Tim,

The first part for copying the dict seems to work nicely but I'm struggling
to get the second part working properly. Let me explain a little more
specifically what I'm trying to do.

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.

I have functions set up for the logging, so I can call it like
logThis(uniquekey) and logThat(uniquekey).

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.


-----Original Message-----
From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org
[mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org]
On Behalf Of Tim Golden
Sent: 30 April 2007 09:41
Cc: python-list at python.org
Subject: Re: Dict Copy & Compare

Robert Rawlins - Think Blue wrote:
> I'm looking for a little advice on dicts, firstly I need to learn how to
> copy a dict, I suppose I could just something like.

> Self.newdict = self.olddict

> But I fear that this only creates a reference rather than an actual copy,
> this means that as soon as I clear out the old one, the new one will
> effectively be empty. What's the best way to ACTUALY copy a dict into a
> variable?

Unless you have specialised needs, you can just say:

d2 = dict (d1)

which will initialise d2 from d1's key/value pairs:

d1 = dict (a=1, b=2)
d2 = dict (d1)
d2['a'] = 5
print d1
print d2


> Next up I'm looking to compare two different dictionaries, then loop
> the unique results that are in each and print them out. Is there a more
> efficient way of doing this other than a loop with an if/else statement?

This comes up not infrequently on the list. I think there's
even a few recipes in the cookbook. One (fairly recent)
technique is to use set versions of your dictionary keys,
but it depends on what you want to do next. From my example

# relies on the fact that dictionary iterators
# iterate over the keys of the dict.

s1 = set (d1)
s2 = set (d2)

# do whatever set-ops you want, eg

s3 = s1 | s2

for key in s3:
   print "Key:", key
   print "d1 =>", d1[key]
   print "d2 =>", d2[key]



More information about the Python-list mailing list