Search code examples
pythonlistnestedalphabeticalsorting

Python - Order nested list in alphabetical way


I have the following list:

["stephane", "philippe", "hélène", ["hugo", "jean-michel", "fernand"], "gustave"]

And I would like to order it like this:

["gustave", "hélène", ["fernand", "hugo", "jean-michel"], "philippe", "stephane"]

NB: If there is a nested list following a user, this list must stay to the right of this user.

In addition to that all nested lists works the same way. It's recursive.


Solution

  • I've used Ned's proposal and came up with this:

    d = {
        "stephane": {}, 
        "philippe": {}, 
        "helene": {
            "hugo": {}, 
            "jean-michel": {},
            "fernand": {},
        }, 
        "gustave": {},
    }
    
    def sort_dict_as_list(d):
        sorted_list = []
        for k, v in sorted(d.items()):
            if k:    
                sorted_list.append(k)
            if v:
                sorted_list.append(v)
        return sorted_list
    
    def sort_recursive(d):
        if d:
            for k, v in d.items():
                d[k] = sort_recursive(v)
            return sort_dict_as_list(d)
        else:
            return d
    
    if __name__ == "__main__":
        print sort_recursive(d)
    

    Output

    python sortit.py
    ['gustave', 'helene', ['fernand', 'hugo', 'jean-michel'], 'philippe', 'stephane']
    

    I haven't tested it thoroughly, but it's a starting point. I was trying to solve it with a list as a data structure, but I ended up nesting recursive functions and it was way too ugly... Ned's proposal was really good.