Qui*_*ill 5 python sorting dictionary
好的,所以我有一个包含字符串中字符位置的字典,但是,我在字典中有单独的字符串,它看起来像这样:
{
'24-35': 'another word',
'10-16': 'content',
'17': '[',
'22': ']',
'23': '{',
'37': ')',
'0-8': 'beginning',
'36': '}',
'18-21': 'word',
'9': '(',
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试按键对这个数组进行排序,使其看起来像这样
{
'0-8': 'beginning',
'9': '(',
'10-16': 'content',
'17': '[',
'18-21': 'word',
'22': ']',
'23': '{',
'24-35': 'another word',
'36': '}',
'37': ')'
}
Run Code Online (Sandbox Code Playgroud)
字典是foreach
通过使用这个字符串来构建的:
' beginning(content[word]{another word})
',并在括号处拆分。
我正在尝试使用@Brian对这个问题的回答对字典进行排序,但是,它在测距过程中按字母顺序排序(因为它们已转换为字符串)(使它说 '0- 8')。
我的问题是:
我该如何转型:
class SortedDisplayDict(dict):
def __str__(self):
return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}"
Run Code Online (Sandbox Code Playgroud)
更具体地说:排序key
为int(key.split('-')[0])
,但仍保持输出范围?
使用键函数sorted
将值转换为int
. 它看起来像:
sorted(d.items(), key=lambda v: int(v[0].split("-")[0]))
Run Code Online (Sandbox Code Playgroud)
此逻辑仅用于排序;sorted
返回的项目仍将使用范围表示法。