I am comfortable using this simple syntax for initializing a dictionary
d = {'a':'Apple','b':'Bat'};
Today, while reading a page, I encountered this weird piece of code
{True:0, False:1}[True];
I was wondering why/how that could work? True
and False
are reserved keywords,
and so, that crazy syntax should be meaningless (for the compiler), but it is
not.
>>> d = {True:0, False:1};
>>> d
{False: 1, True: 0}
And this gets crazier
>>> d = dict(True = 0, False = 1);
SyntaxError: assignment to keyword
>>> d = dict(_True = 0, _False = 1);
>>> d
{'_False': 1, '_True': 0}
In dict()
constructor, True
keyword is not allowed! 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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…