0

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.

Anastaia
  • 31
  • 6
  • 3
    Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – J'e Sep 30 '20 at 10:49
  • 1
    @J'e, the accepted answer in that question looks like my tried solution which does not work for me. – Anastaia Sep 30 '20 at 10:55
  • 1
    @Anastaia are you expecting `d` to have changed? Your code works fine and the result in `sorted_d` looks like what you want. – tzaman Sep 30 '20 at 10:56
  • 1
    @J'e, maybe that solution works only in Python 3.6, but does not work in Python 3.7? – Anastaia Sep 30 '20 at 10:56
  • @Anastaia the accepted answer is out of date but did you look at the other answers? – J'e Sep 30 '20 at 11:04
  • @Anastaia The code you provided in the question works fine for me (and yes, I tested it with Python 3.7) – Matthias Sep 30 '20 at 13:01

2 Answers2

0

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

Joshua Fox
  • 18,704
  • 23
  • 87
  • 147
-1

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)
  • 1
    What do you mean with "or Use this"? That exact code is in that answer, except you changed `x` to `d`, and I'm quite certain that's what you actually did, since you forgot to rename the `sorted_x` variable accordingly. – Kelly Bundy Sep 30 '20 at 12:57