I try to sort a dictionary by value using
sort = sorted(the_dict.items(), key = lambda x : x[1])
but this returns a list of tuples.
How can I return a dict that has the keys sorted in descending value order?
I try to sort a dictionary by value using
sort = sorted(the_dict.items(), key = lambda x : x[1])
but this returns a list of tuples.
How can I return a dict that has the keys sorted in descending value order?
Very close, you need a dict()
constructor to make it a dictionary, note that operator.itemgetter(1)
could replace lambda
d = {'vash': 1, 'the': 5, 'stampede': 12}
new_d = dict(sorted(d.items(), key=lambda x: x[1], reverse = True))
# {'stampede': 12, 'the': 5, 'vash': 1}