In Python 3 sorted()
has an optional parameter key
. And in 3.6+ dict
maintains insertion order.
key
specifies a function of one argument that is used to extract a comparison key from each element in iterable
(for example, key=str.lower
). The default value is None
(compare the elements directly).
Therefore, what OP wants can be accomplished this way.
>>> d = {'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40}
>>> for key, value in sorted(d.items(), key=lambda item: int(item[0])):
... print(key, value)
57480 89
57481 50
57482 18
57483 110
57484 40
57485 82
Or if OP wants to create a new sorted dictionary.
>>> d = {'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40}
>>> d_sorted = {key:value for key, value in sorted(d.items(), key=lambda item: int(item[0]))}
>>> d_sorted
{'57480': 89, '57481': 50, '57482': 18, '57483': 110, '57484': 40, '57485': 82}
d.items()
returns a list of tuples, e.g. ('57480': 89)
and so on. The lambda functions takes this tuple and applies int
function to the first value. And then the result is used for comparison.