好的,所以我有一个包含字符串中字符位置的字典,但是,我在字典中有单独的字符串,这使得它看起来像这样:
{
'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 对字典进行排序的 answer至 this question ,但是,它在范围过程中按字母顺序排序(因为它们已经转换为字符串)(让它说 ' 0-8')。
我的问题是:
如何转换:
class SortedDisplayDict(dict):
def __str__(self):
return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}"
更具体地说:排序后的 key
到 int(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/