Dictionary membership and hashed values


I’m on screen 6 of lesson 424, where you explain how to check if a key is in a dictionary:

It says that with the following code you can do so:

"key" in dictionary

But it looks like it also looks for the hashed value. For example, in this case, it prints “True”:

test = {True: "true"}
print(1 in test)

Is this true in general? Or only for True/1 and False/0?

Because I would imagine that it could cause some mistakes if I have keys of mixed datatype, for example with an integer and a float that have the same hashed value.

If I check for membership of the integer but I have a float with the same hashed value, would the membership test result in True?


Hi @m.bonora, I’ll attempt to answer your query.

I think it should be just the case for booleans and the integers 0 and 1, but not for other data types (as bools and the binary digits - 0 and 1 are interchangeable for Python 3.x+ – see this link).

As I quote from some replies in the post:

In Python 3.x True and False are keywords and will always be equal to 1 and 0.


When converting a bool to an int, the integer value is always 0 or 1, but when converting an int to a bool, the boolean value is True for all integers except 0

(i.e. when the int value is ≥2).

By mixed datatype, do you mean two or more data types?

That might be possible theoretically speaking, and therefore it is suggested to use homogeneous data types (esp. for keys of dictionaries - link) and I would highly recommend unique strings for the keys.

To use meaningful keys in dictionaries, start by thinking of the data structure as an object that contains properties. Each property should be given a name that accurately describes its purpose. For example, if you are creating a dictionary to store information about a person, you could use “name”, “age”, and “address” as your keys. This will make it easy to access the values associated with each key.

Source: 10 Python List Dictionary Naming Best Practices - CLIMB

So it won’t be a good idea to use boolean (or integral) values as keys since there might be key collisions (see the collision below).

Screenshot 2023-01-12 at 9.53.15 PM

Hope this helps!


Hi @masterryan.prof,

Thank you very much for your reply.



@m.bonora, if I managed to solve your doubts, would you mind marking my previous reply as the solution, to benefit other learners with similar doubts?


1 Like