[Tutor] Combining two Dictionaries
Steven D'Aprano
steve at pearwood.info
Sun May 1 10:28:56 CEST 2011
Knacktus 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}
>
> Now d1 holds the address of a dict in memory. [...]
Let me guess... did you learn C before learning Python? Trust me, d1
does not hold the address of anything. Try it and see for yourself:
>>> d1 = {'a': 0, 'b': 0, 'c': 0}
>>> print d1
{'a': 0, 'c': 0, 'b': 0}
Does that look like a memory address to you? Just to be sure:
>>> type(d1)
<type 'dict'>
d1 holds a dict, as expected.
Forget about addresses. This isn't C, or assembly language. All that
low-level stuff about address and memory locations has nothing to do
with Python code and just confuses issues. You can't access memory
addresses in pure Python code. Python abstracts all those low-level
details away, and just cares about objects and names, in the same way
that languages like C abstracts away the only operation a computer
really can do: flip bits on or off.
(However, it is sometimes useful when thinking about the implementation
of the Python virtual machine.)
>> d2 = d1
>
> Now d2 holds the same address of the same dict in memory. d1 and d2
> refer to the same dictionary.
No, and yes. d1 and d2 are two names for the same object:
>>> d2 is d1
True
>> My understanding was that d2 looked at d1 once, grabbed its keys and
>> values,
>> and went off to do its own thing.
>
> You would need to use copy() explicitly.
>
> import copy
>
> d2 = copy.copy(d1) # swallow copy
I think you mean "shallow" copy.
You can do that, but for dicts there is a much simpler way to make a copy:
>>> d3 = d1.copy()
>>> d3 is d1
False
>>> d3 == d1
True
--
Steven
More information about the Tutor
mailing list