Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
'dict()' Has an Exception?
#1
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!
buran write Nov-04-2022, 08:26 AM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply
#2
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Thank you so much! That makes a lot of sense now.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a dict in dict cherry_cherry 4 76,319 Apr-08-2020, 12:25 PM
Last Post: perfringo
  During handling of the above exception, another exception occurred Skaperen 7 26,936 Dec-21-2018, 10:58 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020