[Tutor] Combining two Dictionaries

Andre Engels andreengels at gmail.com
Sun May 1 07:29:37 CEST 2011


On Sun, May 1, 2011 at 5:49 AM, Ryan Strunk <ryan.strunk at gmail.com> wrote:

> When I initialize the class which holds these dictionaries, though, I need
> to make sure that all the keys contained in d2 match the keys of d1. Thus I
> tried:
> d1 = {'a': 0, 'b': 0, 'c': 0}
> d2 = d1
> My understanding was that d2 looked at d1 once, grabbed its keys and values,
> and went off to do its own thing.  Just as if you typed:
> x = 3
> y = x
> x = 6
> y still holds the value 3.
> This turns out not to be the case with dictionaries, and I'm not sure why
> this is so. Why when you change a dictionary's keys in place does a copied
> dictionary take on the new values?
> Thanks for any help you can provide.

To answer your question, we have to look at Python's data model, which
differs from that in other languages. What

y = x

does, is to calculate the object x and give it the name y, apart from
whatever names it may or may not have already. Thus, it does _not_
make a copy, but x and y are two different names of the _same_ object.
What happens in your example, is that you give the object 3 the name
x, then give the object 3 (the outcome of the 'calculation' x) the
name y, then give the object 6 the name x. After that y is still a
name for 3. But if you're working with dictionaries, you're probably
doing something like this:

d1 = {'a': 0, 'b': 0, 'c': 0}  # You create a dictionary and give it the name d1
d2 = d1 # You give _the same_ dictionary the name d2
d1['c'] = 1 # You _change_ the dictionary by changing its value for
the key c. d1 and d2 still are names for the _same_ dictionary

Just like in the integer situation, d2 is still a name for the same
object as it was before, but this time _the object itself has
changed_. And d2 'sees' the change of the object.


-- 
André Engels, andreengels at gmail.com


More information about the Tutor mailing list