Search code examples
pythonsortinglambdapython-3.7built-in

Sorting python dict by value in Python 3.7


I have a dict like the following:

d = {"string0": 0, "string2": 2, "string1": 1}

I want to sort this by int values so that it would like:

d = {"string0": 0, "string1": 1, "string2": 2}

I know that I can sort lists with the help of built-in function sorted() specifying key argument with lambda function like the following:

sorted_d = {k: v for k, v in sorted(d.items(), key=lambda i: i[1])}
       

But for some reason it seems to not work, the dict remains as original.


Solution

  • You can follow this answer

    Click here

    or Use this:

    d = {"string0": 0, "string2": 2, "string1": 1}
    sorted_x = sorted(d.items(), key=lambda kv: kv[1])
    print(sorted_x)