Python - DICT 字典排序 - OrderedDict

 官方地址: https://docs.python.org/2/library/collections.html#collections.OrderedDict

>>> # regular unsorted dictionary

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



>>> # dictionary sorted by key

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

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



>>> # dictionary sorted by value

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

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



>>> # dictionary sorted by length of the key string

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

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

 

不要在意输出时候,OrderedDict在前面,他和字典一样的用,没区别

你可能感兴趣的:(python)