-2

I’m encountering this issue where I have a dict: map-x-to-y = {} and fill it with values such as map-x-to-y[some-string] = counter.

But afterwards, If i try to call sorted I keep on getting ‘list’ object not callable error.

I tried with OrderedDict and with sorted and none of this works. Also, I checked the type of map-x-to-y and it is ‘dict’.

My goal is to sort map-x-to-y in a descending order by value.

Jane-Claire
  • 179
  • 1
  • 11
  • 3
    can you share the actual version of the code you have? – Moinuddin Quadri Aug 31 '18 at 16:46
  • @timgeb just an example – Jane-Claire Aug 31 '18 at 16:47
  • 3
    Your examples should be runnable, i.e. [MCVE]. – timgeb Aug 31 '18 at 16:47
  • `sorted` returns a list. It won't return a `dict`. Maybe you want a list of `tuple`s? – mypetlion Aug 31 '18 at 16:48
  • Possible duplicate of [sort dict by value python](https://stackoverflow.com/questions/16772071/sort-dict-by-value-python) – mad_ Aug 31 '18 at 17:02
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. – Prune Aug 31 '18 at 17:16

1 Answers1

1

Some key points

  1. sorted is for list not dict. Unless you know how to represent your dict as a list. Best answer is here. My method is below
  2. You need to somehow represent your dict as a list
  3. you also need to swap keys for values and values for keys
  4. By value I presume you want your returned list to be sorted by descending order of the value in the map

Try this

In [12]: humans
Out[12]: {'Ashley': 33, 'Danny': 33, 'Jackie': 12, 'Jenny': 22}

In [13]: sorted([ (y,x) for x,y in humans.items()])[::-1]
Out[13]: [(33, 'Danny'), (33, 'Ashley'), (22, 'Jenny'), (12, 'Jackie')]

Explanation

  • use items to convert your dict to a list of tuples
  • use list comprehension to switch the pairs around
  • sort the returned list
  • reverse it
Srini
  • 1,619
  • 1
  • 19
  • 34