为什么在Python中使用基于字典的字符串格式时没有引号?

Xia*_*Wei 3 python python-2.7

我可能有一个愚蠢的问题:

x = {'a':1,'b':2,'c':3}
print "%(a)s" % x   # works fine
print "%('a')s" % x  # failed
Run Code Online (Sandbox Code Playgroud)

有人能告诉我为什么吗?

vau*_*tah 10

%(a)sa从中检索现有密钥的值x.

%('a')s尝试获取不存在的'a'键(带引号)的值,并导致出现错误.

简单的代码示例:

>>> x = {"'a'": 'a within quotes', 'a': 'no quotes'}
>>> "%('a')s" % x
'a within quotes'
>>> "%(a)s" % x
'no quotes'
Run Code Online (Sandbox Code Playgroud)