<p>您可以使用python2.7中添加的<code>OrderedDict</code>dictionary子类来保持键的插入顺序。这只会影响字典本身的显示方式,所有其他操作都与常规字典相同。使用它可以让你更清楚地看到它的内容(但工作方式和你以前一样,那是可以的)。在</p>
<pre><code>>>> symbolMap = map(chr, range(33,64) + range (91,96) + range(123,126))
>>> symbolMap
['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.',
'/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<',
'=', '>', '?', '[', '\\', ']', '^', '_', '{', '|', '}']
>>> from collections import OrderedDict
>>> counter = OrderedDict((chr(c),0) for c in range(33,64) + range(91,96) + range(123,126))
>>> counter
OrderedDict([('!', 0), ('"', 0), ('#', 0), ('$', 0), ('%', 0), ('&', 0),
("'", 0), ('(', 0), (')', 0 ), ('*', 0), ('+', 0), (',', 0), ('-', 0),
('.', 0), ('/', 0), ('0', 0), ('1', 0), ('2', 0), ('3', 0 ), ('4', 0),
('5', 0), ('6', 0), ('7', 0), ('8', 0), ('9', 0), (':', 0), (';', 0),
('<', 0), ('=', 0 ), ('>', 0), ('?', 0), ('[', 0), ('\\', 0), (']', 0),
('^', 0), ('_', 0), ('{', 0), ('|', 0), ('}', 0)])
>>> counter['#'] = counter['#']+1
>>> counter
OrderedDict([('!', 0), ('"', 0), ('#', 1), ('$', 0), ('%', 0), ('&', 0),
("'", 0), ('(', 0), (')', 0 ), ('*', 0), ('+', 0), (',', 0), ('-', 0),
('.', 0), ('/', 0), ('0', 0), ('1', 0), ('2', 0), ('3', 0 ), ('4', 0),
('5', 0), ('6', 0), ('7', 0), ('8', 0), ('9', 0), (':', 0), (';', 0),
('<', 0), ('=', 0 ), ('>', 0), ('?', 0), ('[', 0), ('\\', 0), (']', 0),
('^', 0), ('_', 0), ('{', 0), ('|', 0), ('}', 0)])
</code></pre>
<p>你并不是真的说你想要字典做什么,但是从它的名字和内容来看,你似乎想要计算某些字符的出现。在Python2.7中,<code>collections</code>模块还有另一个名为<code>Counter</code>的新类,它是为此而设计的。以下是如何使用它:</p>
^{2}$