保留python字典顺序 - (python dict的延续)

时间:2012-11-05 02:33:38

标签: python list dictionary python-2.7

List duplicate data concatenation in python

这是列表问题的继续,但在这里我想保留dict的顺序

listData=[('audioVerify', '091;0'), ('imageVerify', 'icon091.gif'), ('bufferVerify', '\x01?')]
    methodList = {}
for item in listData:
    methodList.setdefault(item[0],[]).append(item[1:])
for method in methodList:
    arguments = methodList[method]
    s = [method,arguments]
    print s

当我迭代列表时,它给出了以下

  ['audioVerify', [('091;0',)]]
  ['bufferVerify', [('\x01?',)]]
  ['imageVerify', [('icon091.gif',)]]

但是我可以保留订单的可能性如下:

  ['audioVerify', [('091;0',)]]
  ['imageVerify', [('icon091.gif',)]]
  ['bufferVerify', [('\x01?',)]]

1 个答案:

答案 0 :(得分:8)

我有医生orderedOrderedDict

来自examples

>>> from collections import 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)])

如果你有旧版本的python,consult this other SO question