<p>你想要的叫做<a href="http://en.wikipedia.org/wiki/Associative_array" rel="noreferrer">associative array</a>。在python中,这些称为<a href="http://docs.python.org/tutorial/datastructures.html#dictionaries" rel="noreferrer">dictionaries</a>。</p>
<blockquote>
<p>Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, <strong>dictionaries are indexed by keys, which can be any immutable type</strong>; strings and numbers can always be keys. </p>
</blockquote>
<pre><code>myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"
</code></pre>
<p>创建上述dict的另一种方法:</p>
<pre><code>myDict = {"john": "johns value", "jeff": "jeffs value"}
</code></pre>
<p>访问值:</p>
<pre><code>print(myDict["jeff"]) # => "jeffs value"
</code></pre>
<p>获取密钥(在Python v2中):</p>
<pre><code>print(myDict.keys()) # => ["john", "jeff"]
</code></pre>
<p>在Python 3中,您将得到一个<code>dict_keys</code>,这是一个视图,效率更高一些(有关详细信息,请参见<a href="https://docs.python.org/3/library/stdtypes.html#dict-views" rel="noreferrer">views docs</a>和<a href="https://www.python.org/dev/peps/pep-3106/" rel="noreferrer">PEP 3106</a>)。</p>
<pre><code>print(myDict.keys()) # => dict_keys(['john', 'jeff'])
</code></pre>
<hr/>
<p>如果您想了解python字典的内部内容,我建议您使用这个大约25分钟的视频演示:<a href="https://www.youtube.com/watch?v=C4Kc8xzcA68" rel="noreferrer">https://www.youtube.com/watch?v=C4Kc8xzcA68</a>。它被称为“伟大的字典”。</p>