python - 如何按版本键对字典进行排序

标签 python sorting dictionary key versions

输入:

foo = {
    'testing-1.30.5': ['The', 'quick'],
    'testing-1.30.12': ['fox', 'jumped', 'over'],
    'testing-1.30.13': ['the'],
    'testing-1.30.4': ['lazy', 'dog'],
    'testing-1.30.1': ['brown'],
    'testing-1.30.3': ['the'],
    'testing-1.30.6': ['brown'],
    'testing-1.30.2': ['fox', 'jumped', 'over'],
    'testing-1.30.14': ['lazy', 'dog'],
    'testing-1.30.8': ['the'],
    'testing-1.30.0': ['The', 'quick'],
    'testing-1.30.10': ['The', 'quick'],
    'testing-1.30.11': ['brown'],
    'testing-1.30.7': ['fox', 'jumped', 'over'],
    'testing-1.30.9': ['lazy', 'dog']
}

进行一些排序

bar = sortfoo(foo)

期望的输出:

for item in bar:
    print '{}: {}'.format(item, bar[item])



testing-1.30.0: ['The', 'quick']
testing-1.30.1: ['brown']
testing-1.30.2: ['fox', 'jumped', 'over']
testing-1.30.3: ['the']
testing-1.30.4: ['lazy', 'dog']
testing-1.30.5: ['The', 'quick']
testing-1.30.6: ['brown']
testing-1.30.7: ['fox', 'jumped', 'over']
testing-1.30.8: ['the']
testing-1.30.9: ['lazy', 'dog']
testing-1.30.10: ['The', 'quick']
testing-1.30.11: ['brown']
testing-1.30.12: ['fox', 'jumped', 'over']
testing-1.30.13: ['the']
testing-1.30.14: ['lazy', 'dog']

理想情况下,我希望这是Pythonic的,因为我不会做一些疯狂的事情,比如将 key 拆分成组件并基于此构建一个新字典;

我尝试过的:

from collections import OrderedDict
od = OrderedDict(sorted(foo.items()))
    print '{}: {}'.format(item, od[item])

谢谢

最佳答案

明白了!没关系,找到了 LooseVersion/strict 版本

from distutils.version import LooseVersion
from collections import OrderedDict

orderedKeys = sorted(foo, key=LooseVersion)

odict = OrderedDict((key, foo[key]) for key in orderedKeys)

for item in odict:
     print '{}: {}'.format(item, odict[item])

关于python - 如何按版本键对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39839726/

相关文章:

python - 使用 ConfigObj 或 PyYaml 将字典对提取到交互式工作区中

python - 检查列表是否与元组完全相同

java - 如何使用 Elastic 对最后的 Null 进行排序?

Python:双重排序

python - 插入排序的伪代码是否正确?

c++ - 在 map 中使用 struct 作为键时不调用 < 运算符的重载?

c++ - 存储定义列表以实现最快查找的最佳方式

python - django 标记 - 按标记过滤

Python 通过子进程或其他方法加速命令行调用

python - 使用 operator.itemgetter 对字典进行排序