-2

I know that this problem has been discussed, but none of the answers refer to a string as a key. I would like to sort a dictionary by a value - descending and ascending. Here are my sketches:

def ascending(d):
    from operator import itemgetter
    sorted(d.items(), key=itemgetter(1))
    return d

f={'a': 2, 'c': 1, 'f': 5, 'e': 4}
g={'s': 3, 'y': 1, 'r': 7, 'h': 4}

print(hj(f))

def descending(d):
    from operator import itemgetter
    sorted(d.items(), key=itemgetter(1), reverse=True)
    return d
print(jh(g))

However, I get:

{'a': 2, 'c': 1, 'f': 5, 'e': 4}
{'h': 4, 'r': 7, 'y': 1, 's': 3}

What am I doing wrong? How can I improve the code?

OK, a little ask for explanation: I have solved problem, using:

def ascending(d):
        from operator import itemgetter
        p=sorted(d.items(), key=itemgetter(1))
        return p

    f={'a': 2, 'c': 1, 'f': 5, 'e': 4}
    g={'s': 3, 'y': 1, 'r': 7, 'h': 4}

    print(hj(f))

    def descending(d):
        from operator import itemgetter
        p=sorted(d.items(), key=itemgetter(1), reverse=True)
        return p
    print(jh(g))

How does sorted() works, if it doesn't affected d in 'return d'?

fgh
  • 169
  • 1
  • 3
  • 15
  • Possible duplicate of [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – DeepSpace Dec 26 '18 at 20:40
  • I have viewed this so-called 'duplicate' before asking and I don't know, what is so different in my solution that it doesn't work. – fgh Dec 26 '18 at 20:44
  • OK, I have improved now. – fgh Dec 26 '18 at 20:49

1 Answers1

0

... but none of the answers refer to a string as a key.

That's not relevant.

What am I doing wrong?

There is a big difference between sort() and sorted(). The 1st is evaluated for side effects, and returns None. The 2nd leaves its argument untouched, and creates a brand new list in sorted order.

    sorted(d.items(), key=itemgetter(1))
    return d

You evaluated an expression (which did not change d), and then silently discarded the result. Then you returned the same old d.

You want to return sorted( ... ) instead.

How can I improve the code?

Thank you for asking, that's a terrific question! Do keep asking it of yourself.

PEP8 asks that you put import statements at top of source file, please.

J_H
  • 17,926
  • 4
  • 24
  • 44