Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 735
tajir12457 Avatar asked Nov 04 '25 11:11

tajir12457


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}]
like image 159
Henrik Bo Avatar answered Nov 06 '25 01:11

Henrik Bo


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)
like image 35
Andrej Kesely Avatar answered Nov 06 '25 02:11

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!