字典实战——在Python 3.X 和 2.7 中的字典改变—— has_key 方法在3.X中已死:in 万岁!
最后,广泛使用的字典 has_key
键存在测试方法在 3.X 中消失了。作为替代,使用 in
成员表达式,或有默认测试的 get
(其中,通常 in
更可取):
>>> D
{'b': 2, 'c': 3, 'a': 1}
>>> D.has_key('c') # 2.X only: True/False
AttributeError: 'dict' object has no attribute 'has_key'
>>> 'c' in D # Required in 3.X
True
>>> 'x' in D # Preferred in 2.X today
False
>>> if 'c' in D: print('present', D['c']) # Branch on result
...
present 3
>>> print(D.get('c')) # Fetch with default
3
>>> print(D.get('x'))
None
>>> if D.get('c') != None: print('present', D['c']) # Another option
...
present 3
总结一下,字典的故事在 3.X 中改变了很多。如果在 2.X 中工作并关心 3.X 的兼容性(或认为某一天可能会),下面是一些指南。在本节已经遇到的 3.X 改变中:
- 第一个(字典 comprehension)只能在 3.X 和 2.7 中编码。
- 第二个(字典视图)只能在 3.X 中编码,在 2.7 中使用特殊方法名称才行。
然而,最后三个技术 —— sorted
,手动比较和 in
—— 可以在今天的 2.X 中编码来减轻在未来 3.X 迁移的难度。
推荐文章: