好的,所以我有一个包含字符串中字符位置的字典,但是,我在字典中有单独的字符串,这使它看起来像这样:
{
'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])
,但仍保留输出范围?
答案 0 :(得分:4)
使用sorted
的键功能将值转换为int
。它看起来像是:
sorted(d.items(), key=lambda v: int(v[0].split("-")[0]))
此逻辑仅用于排序; sorted
返回的项目仍将使用范围表示法。
答案 1 :(得分:4)
您可以将字典转换为元组列表(键值对),然后根据键中的第二个数字对它们进行排序(如果它是连字符。)
>>> data = {'24-35': 'another word', '10-16': 'content', '17':
... '[', '22': ']', '23': '{', '37': ')', '0-8': 'beginning', '36': '}',
... '18-21': 'word', '9': '('}
>>> from pprint import pprint
>>> pprint(sorted(data.items(),
... key=lambda x: int(x[0].split("-")[1] if "-" in x[0] else x[0])))
[('0-8', 'beginning'),
('9', '('),
('10-16', 'content'),
('17', '['),
('18-21', 'word'),
('22', ']'),
('23', '{'),
('24-35', 'another word'),
('36', '}'),
('37', ')')]
此处,关键部分是lambda x: int(x[0].split("-")[1] if "-" in x[0] else x[0])
。我们检查-
中是否有x[0]
,如果它存在,那么我们会根据-
进行拆分并获取索引1
处的元素,基本上是-
之后的数字1}}。如果密钥没有-
,则将字符串原样转换为int
。
如果您想维护词典本身的项目顺序,那么您可以使用collections.OrderedDict
,就像这样
>>> from collections import OrderedDict
>>> d = OrderedDict(sorted(data.items(),
... key=lambda x: int(x[0].split("-")[1] if "-" in x[0] else x[0])))
>>> for key, value in d.items():
... print(key, value)
...
...
0-8 beginning
9 (
10-16 content
17 [
18-21 word
22 ]
23 {
24-35 another word
36 }
37 )
答案 2 :(得分:1)
>>> d = {
'24-35': 'another word',
'10-16': 'content',
'17': '[',
'22': ']',
'23': '{',
'37': ')',
'0-8': 'beginning',
'36': '}',
'18-21': 'word',
'9': '(',
}
>>> pprint(sorted(d.items(), key=lambda x: int(x[0].partition('-')[0])))
[('0-8', 'beginning'),
('9', '('),
('10-16', 'content'),
('17', '['),
('18-21', 'word'),
('22', ']'),
('23', '{'),
('24-35', 'another word'),
('36', '}'),
('37', ')')]