Question

I have a nested list in which I want to sort by the inner and outer elements. I have looked at other solutions on stackoverflow and tried several but none of them work the way I want them to. Below, I've presented four attempts that don't work. The comments for each block of code speak for themselves as to what I'm doing and what I want to accomplish.

from operator import itemgetter

# a representation of my real data to be sorted
list_1 = [['key_e', ['v4eee', 'v1eee', 'v3eee', 'v2eee']], ['key_d', ['v4ddd', 'v1ddd', 'v3ddd', 'v2ddd']], ['key_a', ['v4aaa', 'v1aaa', 'v3aaa', 'v2aaa']], ['key_c', ['v4ccc', 'v1ccc', 'v3ccc', 'v2ccc']], ['key_b', ['v4bbb', 'v1bbb', 'v3bbb', 'v2bbb']]]

"""
# same data as above but formatted for readability
list_1 =
[
['key_e', ['v4eee', 'v1eee', 'v3eee', 'v2eee']],
['key_d', ['v4ddd', 'v1ddd', 'v3ddd', 'v2ddd']],
['key_a', ['v4aaa', 'v1aaa', 'v3aaa', 'v2aaa']],
['key_c', ['v4ccc', 'v1ccc', 'v3ccc', 'v2ccc']],
['key_b', ['v4bbb', 'v1bbb', 'v3bbb', 'v2bbb']]
]
"""

# when running the code, pick 1 of the 4 below sort methods and comment out the other 3

# sort method #1 that doesn't work the way I want it to
list_1.sort(key = lambda x: x[1])
list_1.sort(key = itemgetter(0))

"""
# sort method #2 that doesn't work the way I want it to
list_1 = sorted(list_1, key = lambda x: (x[0], x[1]))
"""

"""
# sort method #3 that doesn't work the way I want it to
list_1.sort(key = itemgetter(1))
list_1.sort(key = itemgetter(0))
"""

"""
# sort method #4 that doesn't work the way I want it to
list_1.sort(key = itemgetter(0, 1))
"""

# print the sorted data
for d in list_1:
    print d[0] + ',' + d[1][0] + ',' + d[1][1] + ',' + d[1][2] + ',' + d[1][3] + '\r\n'

"""
# what I get using any of the sort methods
key_a,v4aaa,v1aaa,v3aaa,v2aaa
key_b,v4bbb,v1bbb,v3bbb,v2bbb
key_c,v4ccc,v1ccc,v3ccc,v2ccc
key_d,v4ddd,v1ddd,v3ddd,v2ddd
key_e,v4eee,v1eee,v3eee,v2eee

# what I want
key_a,v1aaa,v2aaa,v3aaa,v4aaa
key_b,v1bbb,v2bbb,v3bbb,v4bbb
key_c,v1ccc,v2ccc,v3ccc,v4ccc
key_d,v1ddd,v2ddd,v3ddd,v4ddd
key_e,v1eee,v2eee,v3eee,v4eee
"""
Was it helpful?

Solution

I think you want the sub-lists to be sorted, and the outer list to be sorted. In which case, do it in two steps:

sorted_inner = [[k, sorted(l)] for k, l in list_1]
sorted_outer = sorted(sorted_inner)

This gives me:

sorted_outer == [['key_a', ['v1aaa', 'v2aaa', 'v3aaa', 'v4aaa']], 
                 ['key_b', ['v1bbb', 'v2bbb', 'v3bbb', 'v4bbb']], 
                 ['key_c', ['v1ccc', 'v2ccc', 'v3ccc', 'v4ccc']], 
                 ['key_d', ['v1ddd', 'v2ddd', 'v3ddd', 'v4ddd']], 
                 ['key_e', ['v1eee', 'v2eee', 'v3eee', 'v4eee']]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top