Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.
更好的方法是,尝试一个OrderedDict(假设您想要一个列表)。比常规dict更接近列表,因为键有顺序,就像列表元素有顺序一样。使用常规dict,键的顺序是任意的。
注意,这在Python3和2.7中是可用的。如果您想与早期版本的Python一起使用,可以找到可安装的模块来实现这一点。
你想要的叫做associative array。在python中,这些称为dictionaries。
创建上述dict的另一种方法:
访问值:
获取密钥(在Python v2中):
在Python 3中,您将得到一个
dict_keys
,这是一个视图,效率更高一些(有关详细信息,请参见views docs和PEP 3106)。如果您想了解python字典的内部内容,我建议您使用这个大约25分钟的视频演示:https://www.youtube.com/watch?v=C4Kc8xzcA68。它被称为“伟大的字典”。
相关问题 更多 >
编程相关推荐