python - 通过拆分键对字典进行排序

标签 python sorting dictionary

好的,所以我有一个包含字符串中字符位置的字典,但是,我在字典中有单独的字符串,这使得它看起来像这样:

{
'24-35': 'another word',
'10-16': 'content',
'17': '[',
'22': ']',
'23': '{',
'37': ')',
'0-8': 'beginning',
'36': '}',
'18-21': 'word',
'9': '(',
}

我试图通过键对这个数组进行排序,所以它看起来像这样

{
'0-8': 'beginning',
'9': '(',
'10-16': 'content',
'17': '[',
'18-21': 'word',
'22': ']',
'23': '{',
'24-35': 'another word',
'36': '}',
'37': ')'
}

字典是通过 foreach 遍历此字符串构建的:
'beginning(content[word]{another word})',并在括号处拆分。

我正在尝试使用 @Brian 对字典进行排序的 answerthis question ,但是,它在范围过程中按字母顺序排序(因为它们已经转换为字符串)(让它说 ' 0-8')。

我的问题是:

如何转换:

class SortedDisplayDict(dict):
   def __str__(self):
       return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}"

更具体地说:排序后的 keyint(key.split('-')[0]) 中,但仍保持输出范围?

最佳答案

sorted 使用键函数,将值转换为 int。它看起来像:

sorted(d.items(), key=lambda v: int(v[0].split("-")[0]))

这个逻辑只会用于排序; sorted 返回的项目仍将使用范围表示法。

关于python - 通过拆分键对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30419819/

相关文章:

python - webapp2 self.request.get 返回 nil

mysql - 优化wordpress mysql数据库文件排序415885行

c++ - 在 C++ 中读取 json 文件

algorithm - 哪种k-merge排序在外部排序中效率会更高

python - 使用不区分大小写的字符串访问 python 字典

python - 处理 python 字典以删除不需要的元素并保留所需的元素

python - 在 Snow Leopard 中安装 VPython?

python - 使用 matplotlib 在 x 轴上绘制 datetimeindex 在 pandas 0.15 和 0.14 中创建错误的刻度

python - 如何使用 withcolumn 方法和基于多个条件的过滤器?

php - 对多维数组进行排序 - 保留键的值