Normal dict behavior?

A

antoine

Hi,

Python 2.7.5 (default, Nov 20 2013, 14:20:58)
[GCC 4.7.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.{0.0: None}

The second item disappeared!

Why?
Is it normal?
 
N

Ned Batchelder

Hi,

Python 2.7.5 (default, Nov 20 2013, 14:20:58)
[GCC 4.7.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.{0.0: None}

The second item disappeared!

Why?
Is it normal?

Because 0 == 0.0
 
C

Chris Angelico

Hi,

Python 2.7.5 (default, Nov 20 2013, 14:20:58)
[GCC 4.7.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.{0.0: None}

The second item disappeared!

Why?
Is it normal?

There are two things happening here. Firstly:
True

Secondly:
{'spam': 2}

I think you'll agree that, in the second case, Python cannot store
both values. You might say that this ought to be an error, but
certainly it can't return a dict with two values when you attached
them to the same key.

The first part is that a dict is defined on the basis of equality, and
the integer 0 and the floating point 0.0 are equal. So to the dict,
they are just as much equal as the two strings "spam" are, and it's a
duplicate key.

Obviously the dict can't be defined on the basis of object identity,
as you'd then have to carefully intern all strings used, etc, etc.
(Though an identity-based mapping would have some value. i'm sure you
could make a MutableMapping that internally maps id(key) to (key,
value) and handles everything uniquely. Might already exist, even. But
it's definitely not what the inbuilt dict should do.) So the two
arguable points are:

1) Should 0 and 0.0 compare equal? Both choices make sense, and
different languages choose differently, but Python has declared that
numerics representing the same number are equal. So, this one isn't
changing.

2) Should the dict give you some kind of notification when it
overwrites a key/value pair during construction/display? Maybe. It
does seem a little illogical to write something in that will get
ignored, so I could imagine this giving a warning or error. The
question is probably: How much do you gain by having the dict check
for this, and how much effort is it therefore worth? Considering how
pervasive the dict is in Python's own internals, not to mention how
many times it's used in user-level code, any performance hit would
multiply out, so it would need to be extremely beneficial.

But it's a possibility for a linter, maybe.

ChrisA
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top