Sort a list of dictionaries without knowing the keys/values

Viewed 247

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'.

2 Answers

Assuming that all the keys are the same this may be what you need:

list_to_be_sorted = [{"name": 3}, {"name": 2}, {"name": 4}, {"name": 1}]
sorted_list = sorted(list_to_be_sorted, key=lambda k: k[[*k][0]])

Output:

[{'name': 1}, {'name': 2}, {'name': 3}, {'name': 4}]

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'))
Related