The unexpected running outcomes for Dictionary, Try Except and For-Loop

One of my favourite leisure activities is wandering on Stack Overflow. There are many interesting questions over there about Python. Indeed, some of the questions we may never meet in our life. However, the knowledge behind it is quite interesting, which is even more interesting than the question itself.

In this article, I’ll pick up three “mysterious” behaviours in Python and try to explain them. Hopefully, the knowledge may be able to help someone in some “mysterious” aspects 🙂

Image by S. Hermann & F. Richter from Pixabay

Do you know that a Python dictionary can use any hashable objects as the key? Yes, that means we can even use numbers as the keys. Someone may think that’s a “good” idea because we can use expressions in the brackets my_dict[1+1]. No, please don’t. I’ll show you.

Let’s define a dictionary that uses integer, float and string as the keys. They are all “1” by the meaning.

my_dict = {
1: 'one (integar)',
'1': 'one (string)',
1.0: 'one point zero (float)'
}

Now, let’s try to get the values using the keys.

my_dict[1]
my_dict['1']
my_dict[1.0]

Hold on, the first one is not right. It looks like the value of my_dict[1] has been overwritten by my_dict[1.0]. Let’s try a different order to verify it.

my_dict = {
1.0: 'one point zero (float)',
1: 'one (integar)',
'1': 'one (string)'
}

This time, the value of my_dict[1] overwrote the my_dict[1.0]. Therefore, whoever defined later will overwrite the previous one. That means the key 1 and 1.0 are the same.

The Reason Behind It

Let’s have a look at the Python official documentation first:

hash(object)

Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).

It basically tells the reason already. The keys of the dictionary that we passed in will be hashed for comparing purposes, and unfortunately, the hash values for a certain number of different types are the same. We can verify this.

print(hash(1))
print(hash(1.0))
print(hash('1'))

In fact, this is not unique to Python, but in Java, too. If you implement hashCode then, for things to work correctly, you must make sure x.equals(y) implies x.hashCode() == y.hashCode().

Back to Python, 1.0 == 1 is True in Python. Therefore, the hash function has to be…

Continue reading: https://towardsdatascience.com/three-mysterious-behaviours-of-python-95c9dffa88fe?source=rss—-7f60cf5620c9—4

Source: towardsdatascience.com