gatto gatto - 6 months ago 11
Python Question

List ordering based on dict key value with string number

I have a simple

list
of
dict
objects that I would like to order based on the values of the
number
keys. I could find here a solution that worked properly until I had values between
0-99
, but since there are 3 char long strings it doesn't work anymore.

It looks my base list:

base_list = [{'number':"123", 'key2':"sample value"},{'number':"3", 'key2':"sample value"},{'number':"55", 'key2':"sample value"},{'number':"43", 'key2':"sample value"},]


And this is what I would like to achive:

base_list = [{'number':"3", 'key2':"sample value"},{'number':"43", 'key2':"sample value"},{'number':"55", 'key2':"sample value"},{'number':"123", 'key2':"sample value"},]


And this is what I got:

base_list = [{'number':"123", 'key2':"sample value"},{'number':"3", 'key2':"sample value"},{'number':"43", 'key2':"sample value"},{'number':"55", 'key2':"sample value"},]
#123,3,43,55 instead of 3,43,55,123


I assume the problem is the values that I use for sorting the list are strings, but unfortunately I can't use integers.

Is it possible to solve the problem without int type values? Or it's not a problem?

This is how I'm doing it now:

sortedList = sorted(base_list, key=itemgetter('number'))

Answer

To sort not in-place, use sorted instead of list.sort,

base_list = [{'number':"123", 'key2':"sample value"},{'number':"3", 'key2':"sample value"},{'number':"55", 'key2':"sample value"},{'number':"43", 'key2':"sample value"},]

result = sorted(base_list, key=lambda x: int(x['number']))

print(result)
# Output
[{'key2': 'sample value', 'number': '3'}, {'key2': 'sample value', 'number': '43'}, {'key2': 'sample value', 'number': '55'}, {'key2': 'sample value', 'number': '123'}]