字典实战——在Python 3.X 和 2.7 中的字典改变——在3.X中排序字典键
首先,因为 keys
在3.X中不返回列表,在2.X中通过已排序键扫描字典的传统编程模式在3.X不起作用:
>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> D
{'b': 2, 'c': 3, 'a': 1}
>>> Ks = D.keys() # Sorting a view object doesn't work!
>>> Ks.sort()
AttributeError: 'dict_keys' object has no attribute 'sort'
要解决这个问题,在3.X中必须要么手动转为列表,要么对 keys
视图或字典本身使用sorted
调用(在第4章中介绍过,在本章讲述):
>>> Ks = list(Ks) # Force it to be a list and then sort
>>> Ks.sort()
>>> for k in Ks: print(k, D[k]) # 2.X: omit outer parens in
prints
...
a 1
b 2
c 3
>>> D
{'b': 2, 'c': 3, 'a': 1}
>>> Ks = D.keys() # Or you can use sorted() on the keys
>>> for k in sorted(Ks): print(k, D[k]) # sorted() accepts any
iterable
... # sorted() returns its result
a 1
b 2
c 3
在这些方法中,3.X中使用字典的键迭代器很可能更可取,而且在2.X中也起作用:
>>> D
{'b': 2, 'c': 3, 'a': 1} # Better yet, sort the dict directly
>>> for k in sorted(D): print(k, D[k]) # dict iterators return keys
...
a 1
b 2
c 3
推荐文章: