Sorting python dict by value in Python 3.7

144 views Asked by At

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.

2

There are 2 answers

1
justAnAnotherCoder On BEST ANSWER

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)
0
Joshua Fox On

Your key is 1[1] which is invalid Python. You want i[1]. That change will do it.