Question about dictionaries (Question about is ?)

Matt Gushee mgushee at havenrock.com
Sat Jan 8 11:21:48 EST 2000


Felix Thibault <felixt at dicksonstreet.com> writes:

> >>> text = 'spam-a-lam-a-spama'
> >>> names = {'spam': text[:4]}
> >>> dict1 = {text[:4]: {text[-5:-1]: 'eggs'}}
> >>> dict2 = {names[text[:4]]: {names[text[-5:-1]]: 'eggs'}}
> 
> with the difference being:
> 
> >>> dict1.keys()[0] is dict1['spam'].keys()[0]
> 0
> >>> dict2.keys()[0] is dict2['spam'].keys()[0]
> 1
> 
> ...but I'm new to programming as well as to Python, so I'm not sure what
> this means-

Holy Dangerous Loops of Logic, Batman! Are you the reincarnation of
Nikola Tesla or what?

I'm not sure what it means either, but what seems to be happening is
that dict1['spam'].keys()[0] returns a reference to text[-5:-1] --
i.e.:

        'spam-a-lam-a-spama'
                    ^^^^
whereas dict2['spam'].keys()[0] returns a reference to text[:4], --
i.e.:

        'spam-a-lam-a-spama'
         ^^^^
... and the two just happen to have the same string value. 

>>> dict1.keys()[0] == dict1['spam'].keys()[0]
1

> does dict2
> take up less memory,

I don't know enough about the internals of Python to be sure, but I
can't imagine it would. dict1 references two different objects with
the value 'spam'; dict2 references a single spammy object twice; but
they both contain the same number of object references.

> or something, or is this just a Stupid Programming
> Trick?

Hah! Your next challenge is to find a use for this interesting
technique. If you can do that, it won't be just a Stupid Programming
Trick ;-)

-- 
Matt Gushee
Portland, Maine, USA
mgushee at havenrock.com
http://www.havenrock.com/



More information about the Python-list mailing list