Dict Copy & Compare

Tim Golden mail at timgolden.me.uk
Mon Apr 30 04:40:53 EDT 2007


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 new
> variable?

Unless you have specialised needs, you can just say:

d2 = dict (d1)

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

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

</code>


> Next up I'm looking to compare two different dictionaries, then loop through
> 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
above:

<code>
# 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]

</code>

TJG



More information about the Python-list mailing list