Skip to content Skip to sidebar Skip to footer

Sorting By Value In A Dictionary If The Value Is A List

I know that dictionaries aren't sortable, that being said, I want the representation of the dictionary that is sorted upon that value which is a list. Example: some_dict= { 'a

Solution 1:

You're on the right track, but you can't put a for-loop in a lambda (hence the error):

>>> sorted(some_dict.items(), key=lambda x: x[1][0])
[('a', [0, 0, 0, 0, 0]), ('c', [800, 30, 14, 14, 0]), ('b', [1400, 50, 30, 18, 0]), ('d', [5000, 100, 30, 50, 0.1]), ('for fun', [140000, 1400, 140, 140, 0.42])]

If you want to keep this order in a dictionary, you can use collections.OrderedDict:

>>> from collections import OrderedDict
>>> mydict = OrderedDict(sorted(some_dict.items(), key=lambda x: x[1][0]))
>>> print(mydict)
OrderedDict([('a', [0, 0, 0, 0, 0]), ('c', [800, 30, 14, 14, 0]), ('b', [1400, 50, 30, 18, 0]), ('d', [5000, 100, 30, 50, 0.1]), ('for fun', [140000, 1400, 140, 140, 0.42])])
>>> print(mydict['a'])
[0, 0, 0, 0, 0]

Solution 2:

lambdas are anonymous functions, but they can only execute expressions in Python:

lambda pair: pair[1][0]

You could also write it verbosely:

def sorting_func(pair):
    key, value = pair
    return value[0]

sorted(some_dict.items(), key=sorting_func)

Post a Comment for "Sorting By Value In A Dictionary If The Value Is A List"