Python Forum

Full Version: 'dict()' Has an Exception?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey guys, please let me know if you have an answer to this (copy and paste into your IDE):
x = {
    0: "value 0",
    1: "value 1",
    2: "value 2",

    True: False
}
print(x.get(0))
print(x.get(1))
print(x.get(2))

# output will look like this:
# value 0
# False
# value 2
For some reason, only x.get(1) returns "False," and any other number or character will return with its dict definition. Does anyone know why that is? Thanks!
Print x to check what your dict looks like

x = {0:"value 0", 1:"value 1", 2:"value 2", True:False}
print(x)
Output:
{0: 'value 0', 1: False, 2: 'value 2'}
TLTR: Key True is same as 1 thus last seen wins.


Check
https://peps.python.org/pep-0285/

Quote:The bool type would be a straightforward subtype (in C) of the int type, and the values False and True would behave like 0 and 1 in most respects (for example, False==0 and True==1 would be true) except repr() and str().

Quote:6. Should bool inherit from int?

=> Yes.

In an ideal world, bool might be better implemented as a separate integer type that knows how to perform mixed-mode arithmetic. However, inheriting bool from int eases the implementation enormously (in part since all C code that calls PyInt_Check() will continue to work – this returns true for subclasses of int). Also, I believe this is right in terms of substitutability: code that requires an int can be fed a bool and it will behave the same as 0 or 1. Code that requires a bool may not work when it is given an int; for example, 3 & 4 is 0, but both 3 and 4 are true when considered as truth values.
Thank you so much! That makes a lot of sense now.