Jign
Jign

Reputation: 149

How to return a sorted dictionary's keys by sorting its values

I have a dictionary like this:

a = {'str1':[int,int,int],'str2':[int,int]}

I want to returns the keys like ['str1', 'str2'] because sum of sum(a[str1]) > sum(a[str2])

I tried to use the sum function:

return sorted(a.keys(), key = lambda a.values(): sum(a.values()))

But it raises an error. TypeError: unsupported operand type(s) for +: 'int' and 'list'

How should I do?

Upvotes: 1

Views: 142

Answers (1)

Shashank
Shashank

Reputation: 13869

The expression sum(family.values()) will try to reduce a list of lists to a sum starting with the initial value 0. When you try to add a list to 0, you get a TypeError because the operation is not supported by either operand.

Try it like this instead:

sorted(family, key=lambda k: sum(family[k]))

The parameter for your lambda expression is k, and the arguments passed to it will be each element of the iterable, which is, in this case, family.keys() which can be shortened to family because dicts can be treated as iterables of their keysets. The value of each element's key will simply be the sum of the dictionary value which is a list.

Upvotes: 2

Related Questions