Search code examples
pythonpython-3.xlistsortingdictionary

Sort a list of dictionaries without knowing the keys/values


A function in my code (F1) returns a list of dictionaries. I need to sort this list of dictionaries and print it out. It doesn't matter if we sort the list ascendingly or descendingly, as long as were are consistent. The problem is, F1 could return an entirely different list of dictionaries every time: the length, the keys, the values, everything could be different, and I couldn't know that in advance.

How can I safely and consistently sort such a list? I have this:

sorted_list = sorted(list_to_be_sorted, key=lambda k: k['name'])

but it doesn't work in my case as I might have a list that doesn't contain a 'name'.


Solution

  • One solution is to use dict.get. If the key doesn't exist in dictionary it returns None (or other default value if you want):

    sorted_list = sorted(list_to_be_sorted, key=lambda k: k.get('name'))
    

    Keep in mind that knowing the type would be important here as you risk getting the following type of error for mismatching value types when the key cannot be found:

    TypeError: '>' not supported between instances of 'str' and 'NoneType'
    

    This situation could come up if the data structure you are dealing with might not always have that key in each piece of data you are trying to sort through.

    To circumvent this, if you do know the type of value you are sorting around, then set the default type in get accordingly.

    Example:

    # string
    k.get('name', '')
    
    # int
    k.get('name', 0)