有序字典

>>>import collections

>>>d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2 }

>>>collections.OrderedDict(sorted(d.items(),key=lambda t:t[1]))

OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])


>>>order_dict = collections.OrderedDict({'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2 })

>>> order_dict
OrderedDict([('orange', 2), ('pear', 1), ('banana', 3), ('apple', 4)])
>>> order_dict.items()
[('orange', 2), ('pear', 1), ('banana', 3), ('apple', 4)]
>>> for dict_item in order_dict:
...     print dict_item
...     print order_dict[dict_item]
...
orange
2
pear
1
banana
3
apple
4


老方法:dict和list配合使用

你可能感兴趣的:(有序字典)