Search code examples
pythonlistdefaultdict

sorting lists in python 3


So, I need to sort this kind of list with some random data in it by first element of second nested list (with elements like 01, 02, 03, etc):

  [['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']], etc]

this random data is later used in defaultdict with some other data, in order to group it together and print it out by key (the keys are numbers like 00553, 00551).

I tried to sort it before putting it to defaultdict but all I am getting sorted out is values of nested list itself..

can anybody please help me, I am new in this.


Solution

  • lis = [['00553', ['01', '3.4']], ['00553', ['02', '2.1']],
          ['00551', ['02', '5.3']], ['00551', ['01', '5.3']],['00551', ['04', '5.3']]]
    import operator
    newlist = sorted(lis, key=operator.itemgetter(1))
    

    result

    >>> newlist
    [['00553', ['01', '3.4']], ['00551', ['01', '5.3']], 
          ['00553', ['02', '2.1']], ['00551', ['02', '5.3']], ['00551', ['04', '5.3']]]