Ok, so I have a dictionary that contains positions of characters in a string, however, I've got individual strings inside the dictionary, which makes it look like this:
{
'24-35': 'another word',
'10-16': 'content',
'17': '[',
'22': ']',
'23': '{',
'37': ')',
'0-8': 'beginning',
'36': '}',
'18-21': 'word',
'9': '(',
}
I'm trying to sort this array by the keys, so that it'd look like this
{
'0-8': 'beginning',
'9': '(',
'10-16': 'content',
'17': '[',
'18-21': 'word',
'22': ']',
'23': '{',
'24-35': 'another word',
'36': '}',
'37': ')'
}
The dictionary is built by foreach
ing through this string:
'beginning(content[word]{another word})
', and splitting at the brackets.
I'm trying to sort the dictionary by using @Brian's answer to this question, however, it sorts by the alphabetically (because they've been transformed to strings) at the ranging process (the thing that makes it say '0-8').
My question is:
How can I transform:
class SortedDisplayDict(dict):
def __str__(self):
return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}"
and more specifically: the sorted key
into int(key.split('-')[0])
, but still keep the output with ranges?