【问题标题】:Preserving python dictionary order - (Continuation of python dict )保留 python 字典顺序 - (python dict 的延续)
【发布时间】:2012-11-05 02:33:38
【问题描述】:

List duplicate data concatenation in python

这是列表问题的延续,但在这里我想保留字典的顺序

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?',)]]

【问题讨论】:

    标签: python list dictionary python-2.7


    【解决方案1】:

    我刚刚什么医生ordered:OrderedDict

    来自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

    【讨论】:

    • 我用的是python2.6 :(还有其他方法吗
    • 嗯。我提供了这个解决方案,因为这个问题被标记为python-2.7
    • 正如 Brian Cain 所说,您应该阅读此thread
    • 很好的例子,但是一旦你想推送新项目,你必须重新创建字典。
    • 不确定为什么 OP 认为这是最佳答案,因为根据问题未满足请求的顺序。该示例以多种方式显示排序,但没有一种具有索引样式的排序;这可以用list[i] 完成并跳过整个OrderedDict。或者在原始保存的情况下,将项目复制到新列表。在上述情况下,OP 需要在使用 ordered 之前添加“值”排序键;这实际上适用于简短的字典/列表...但是如果您有数千个......以及数千个条目会很痛苦。
    猜你喜欢
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 2017-06-08
    • 2020-12-31
    相关资源
    最近更新 更多