Using True / False as keys - how / why does it work?

I find it convenient to use this simple syntax to initialize dictionary

d = {'a':'Apple','b':'Bat'};

Today, while reading the page, I came across this strange piece of code

{True:0, False:1}[True];

I was wondering why / how this could work? Trueand Falseare reserved keywords, and therefore, that crazy syntax should be meaningless (for the compiler), but it is not.

>>> d = {True:0, False:1};
>>> d
{False: 1, True: 0}

And it gets more crazy

>>> d = dict(True = 0, False = 1);
SyntaxError: assignment to keyword
>>> d = dict(_True = 0, _False = 1);
>>> d
{'_False': 1, '_True': 0}

In the constructor, the dict()keyword is Truenot valid! But...


Update
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import keyword
>>> keyword.iskeyword('print');
False
>>> keyword.iskeyword('else');
True
>>> keyword.iskeyword('True');
True
>>> keyword.iskeyword('False');
True
+4
source share
3 answers

( Python 3), True False ( bool(1) bool(0)).

, , . , . :

d = {}
d[True] = "True"
d[False] = "False"

(d = {True: "True", False: "False"}), dict . dicts , , Python. True False , ( ) .

, key/value, - , dict, :

d = dict([(True, "True"), (False, "False")])

, , , . bool Python int, True False, . 1-True, 0.

+5

? True False - , . .

dict. , .

+4

True False - . Python ( 2.7, 3.x):

Python 2.7.6 (default, Jan 29 2014, 21:22:07) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> type(True)
<type 'bool'>
>>> True.__class__.__name__
'bool'
>>> type(False)
<type 'bool'>
>>> False.__class__.__name__
'bool'
>>> hash(True)
1
>>> hash(False)
0
>>> True.__hash__
<method-wrapper '__hash__' of bool object at 0x100134da0>
>>> False.__hash__
<method-wrapper '__hash__' of bool object at 0x100134db8>

, dict .

, Python 3 True False dict():

>>> d = dict(True="true", False="false")
>>> d
{'False': 'false', 'True': 'true'}

, , Python 3 , , . ( , , , .)

+2

Source: https://habr.com/ru/post/1530773/


All Articles