2014年03月07日 星期五 09:45
Python的dict是无序的,这与C++不同,C++默认的map是有序的(基于tree的数据结构),C++ 11引入了unordered_map,实现了无序的map。而Python在collections目录中,有OrderedDict这个容器,可以实现有序的字典。
An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.
代码示例如下:
from collections import OrderedDict od=OrderedDict() od['laoli']='laoli@163.com' od['laozhang']='laozhang@gmail.com' od['laomeng']='mengguang@gmail.com' for k in od: print(k,od[k]) print() d={} d['laoli']='laoli@163.com' d['laozhang']='laozhang@gmail.com' d['laomeng']='mengguang@gmail.com' for k in od: print(k,od[k])
参考资料:
http://docs.python.org/3/library/collections.html#collections.OrderedDict
Zeuux © 2024
京ICP备05028076号