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.
You can follow this answer
or Use this:
d = {"string0": 0, "string2": 2, "string1": 1}
sorted_x = sorted(d.items(), key=lambda kv: kv[1])
print(sorted_x)