python - 用数字表示按键排序字典

标签 python python-2.7 dictionary

我有这个输入,其中每个值的范围是 200:

d = {'600-800': 3, '1800-2000': 3, '1000-1200': 5, '400-600': 1, '2600-2800': 1}

我正在寻找这个预期的顺序:

{'400-600': 1, '600-800': 3, '1000-1200': 5, '1800-2000': 3, '2600-2800': 1}

已经尝试过类似的方法,但是顺序不对:

import collections
od = collections.OrderedDict(sorted(d.items()))
print od

最佳答案

您可以将键拆分为 '-' 部分,并使用第一部分作为整数值对其进行排序。由于键值的性质(当转换为整数时),第二部分与排序无关:

d = {'600-800': 3, '1800-2000': 3, '1000-1200': 5, '400-600': 1, '2600-2800': 1}
import collections
od = collections.OrderedDict(sorted(d.items(),key =lambda x: int(x[0].split("-")[0])))
print od

输出:

OrderedDict([('400-600', 1), ('600-800', 3), ('1000-1200', 5), 
             ('1800-2000', 3), ('2600-2800', 1)])

独库:

相关:

关于python - 用数字表示按键排序字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54389040/

相关文章:

python - 为什么结构报告 "No hosts found"?

python - 类型错误:* 不支持的操作数类型: 'function' 和 'int' BMI 计算器

python - 导入错误:没有名为 'mirror' 的模块

python - 带有 for 循环的嵌套字符串列表

python - 在 Python 2 或 Python 3 上导入 Openpyxl

c# - 为什么这个自定义字典类不起作用 - C# 4.0

python - 从字典中的值列表创建矩阵

python - 重新创建 Web Audio API GainNode 行为

python-2.7 - 嵌套字典中的 has_key

arrays - 不确定如何访问 firebase 数据库中的每个值