3

Suppose I have the following dictionary:

{"A":["u","w"],"B":["t"],"C":["x","y","z"]}

How can I sort the dictionary by number of strings in the list in of each value so that it returns:

[("C",["x","y","z"]), ("A",["u","w"]), ("B":["t"])]

Because the value of "C" has three items in the list, "A" has two, "B" has one. I was thinking something along the lines of:

sorted(d.items(),key=operator.methodcaller(len(),tuple[1]),reverse=True)

Or

sorted(d.items(),key=(string, stringList):(len(stringList),string),reverse=True)

But both do not seem to work. Still quite new to sorting, so thanks for the help!

  • `operator.methodcaller` takes a string as the first paramater, the method to call, `tuple[1]` doesn't exist at the time you call it. Also `key` is a function, not a tuple. – jamylak Apr 18 '13 at 07:51

3 Answers3

2
>>> d = {"A":["u","w"],"B":["t"],"C":["x","y","z"]}
>>> sorted(d.items(), key=lambda x: len(x[1]), reverse=True)
[('C', ['x', 'y', 'z']), ('A', ['u', 'w']), ('B', ['t'])]
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • That was fast! Thank you jamylak, marking your response as the answer in 11 minutes. –  Apr 18 '13 at 07:48
0

You almost had it.

>>> sorted(d, key=lambda x: len(d[x]), reverse=True)
['C', 'A', 'B']

Or, to get the values as well:

>>> sorted(d.items(), key=lambda x: len(x[1]), reverse=True)
[('C', ['x', 'y', 'z']), ('A', ['u', 'w']), ('B', ['t'])]
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
0

Using a lambda:

sorted(d.items(), key=lambda x: len(x[1]), reverse=True)
Yuushi
  • 25,132
  • 7
  • 63
  • 81