pythonsortingdictionaryordereddictionaryordereddict

python sort dictionary by value where each element is a list (by the first element in the list)


I have a dictionary:

dct = {'a' : [1,2] , 'b' : [5,9] , 'c' : [3,8] , 'd' : [0,1]}

I want to sort it by the first element in the value to get:

dct = {'d': [0, 1], 'a': [1, 2], 'c': [3, 8], 'b': [5, 9]}

Is this possible?


Solution

  • You can use sorted() on the key and the value of dict

    >>> dict(sorted(dct.items(), key=lambda x: x[1][0]))
    # -------------------------------x[0] is key, x[1] is value.
    # -------------------------------first element of value is x[1][0]
    {'d': [0, 1], 'a': [1, 2], 'c': [3, 8], 'b': [5, 9]}