How to sort dictionary by key in numerical order Python

后端 未结 4 750
时光取名叫无心
时光取名叫无心 2020-12-01 15:59

Here is the dictionary looks like:

{\'57481\': 50, \'57480\': 89, \'57483\': 110, \'57482\': 18, \'57485\': 82, \'57484\': 40}  

I would

4条回答
  •  时光取名叫无心
    2020-12-01 16:36

    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.

提交回复
热议问题