字典实战——在python 3.x 和 2.7 中的字典改变——在3.x中排序字典键 | 第二部分 类型与操作 —— 第 8 章: 列表和字典 |《学习 python:强大的面向对象编程(第 5 版)》| python 技术论坛-金年会app官方网
首先,因为 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