Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:使用locals()打印字典值_Python_Dictionary_String Formatting_Syntactic Sugar - Fatal编程技术网

Python:使用locals()打印字典值

Python:使用locals()打印字典值,python,dictionary,string-formatting,syntactic-sugar,Python,Dictionary,String Formatting,Syntactic Sugar,Python中最好的工具之一是字符串格式中的locals(): >>> st="asdasd" >>> print "%(st)s" % locals() asdasd 但是,无法使用字典值执行此操作: >>> d={1:2, 3:4} >>> print "%(d[1])s" % locals() Traceback (most recent call last): File "<stdin>", lin

Python中最好的工具之一是字符串格式中的
locals()

>>> st="asdasd"
>>> print "%(st)s" % locals()
asdasd
但是,无法使用字典值执行此操作:

>>> d={1:2, 3:4}
>>> print "%(d[1])s" % locals()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'd[1]'
>d={1:2,3:4}
>>>打印“%(d[1])s”%locals()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
KeyError:'d[1]'
你知道怎么做吗

>>> d={1:2, 3:4}
>>> print '{0[1]}'.format(d)
2
>>> print '{0[d][1]}'.format(locals())
2
>>> print '{[d][1]}'.format(locals())
2
>>>

最后一个只适用于2.7

我不确定我是否能与
本地人
进行语法糖类比。想澄清一下吗?
“%(键)s”%d
?请注意,只有字符串键可以以这种方式使用。Eli,它是一种语法糖,因为
print”名称:%s“%user\u name
可读性较差,但与
print”名称:%(user\u name)s“%locals()
)等效,特别是在长字符串中。它还有助于避免列表参数顺序的混乱,例如,
print“first\u name:%s,last\u name:%s,city:%s”%(last\u name,first\u name,city)”
中的错误不太明显。我想大多数python程序员都会完全不同意您的示例。您似乎只是误解了字符串格式的作用。我也不会把它称为“语法糖“@Jochen Ritzel,想详细阐述一下吗?根据维基百科,语法糖是“……设计用来让事情更容易阅读或表达,同时还有其他表达方式。”我认为这是一个很好的例子。