返回::Python 罕见问题集

::-- huangyi [2006-04-22 15:39:36]

::-- ZoomQuiet [2005-09-06 04:10:30]

1. 问:是否有一种更好的语法来编写字典文本?所有keys都是标识符。?

Q: Is there a better syntax for dictionary literals? All my keys are identifiers.?

答案是肯定的!我也觉得总是要在key的两边打上引号是很烦的事情,特别是编写一个大的字典文本的时候。开始我觉得为它添加一种专门的语法应该是对python的一个有用的改进;比如象这样: {a=1, b=2} 而现在你只能这么写:{'a':1, 'b':2}。但是随后我认识到只要定义一个单行的函数就几乎可以获得这个语法:

Yes! I agree that it can be tedious to have to type the quote marks around your keys, especially for a large dictionary literal. At first I thought it might be a useful change to Python to add special syntax for this; maybe {a=1, b=2} for what you now have to write as {'a':1, 'b':2}. But then I realized that you can almost have this syntax by defining a one-line function:

   1 def Dict(**dict): return dict
   2 
   3 >>> Dict(a=1, b=2, c=3, dee=4)
   4 {'a':1, 'b':2, 'c': 3, 'dee': 4}

有个读者提到 Perl 有一个和这类似的针对hashes的特殊记号; 在Perl里面hash文本可以写成("a", 1, "b", 2} , 也可以写成(a => 1, b => 2)。这是事实,不过并不完全正确

A reader suggested that Perl has a similar special notation for hashes; you can write either ("a", 1, "b", 2} or (a => 1, b => 2) for hash literals in Perl. This is the truth, but not the whole truth. "man perlop" says "The => digraph is mostly just a synonym for the comma operator ..." and in fact you can write (a, 1, b, 2), where a and b are barewords. But, as Dag Asheim points out, if you turn strict on, you'll get an error with this; you must use either strings or the => operator. And Larry Wall has proclaimed that "There will be no barewords in Perl 6."

   1 import types
   2 
   3 def update(x, **entries):
   4     return x