Python Forum

Full Version: List Sorting Problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Sorry I am a novice.

I am trying to sort a custom dictionary consisting of a list of 2-element lists, (lexical entry and definition), using sort() and/or sorted() with sorting keys.

I need to sort using keys both for i) list position (i.e., position 0), and ii) normal alphabetic (case-insensitive) order as used for standard dictionaries.

I know how to each of these things alone, but not both at once, and this does not seem to be a problem of 'successive sorts', but different parameters of one sort. So I am using 'key=str.lower' for normal alphabetic sort, and
'key= itemgetter(0) for sorting on first element.

Perhaps this would be easier with a different data structure?

Thanks!
I am personally lost - I read and reread it and can't comprehend what is needed to be done. So please provide code and sample data along with it (what have you got and how would you like to transform it) and where specifically you stumbled.
%%Here is a list:

list = [ ['pencil', 'writing implement'], ['asteroid', 'space body'], ['Arctic', 'northern pole'] ]

%%I can sort on the first element, here using itemgetter:

sortedlist = sorted(list, key = itemgetter(0))

%%this produces: [ ['asteroid', 'space body'], ['pencil', 'writing implement'], ['Arctic', 'southern pole'] ]

%%but I want: [ ['Arctic', 'southern pole'], ['asteroid', 'space body'], ['pencil', 'writing implement']], that is, I want standard alphabetical dictionary order, which is generally case-insensitive. How do I get it? I could use:

key = str.lower

%%but how do I combine that with itemgetter, for instance, given the argument passed to itemgetter might be 0 or might be something else?
If you adjust your keyfunc a little bit then you can achieve desired result.

Depending how agressive you would like to be in lowering you can use str.casefold or str.lower.

...and don't use list as a name.

>>> data = [['pencil', 'writing implement'], ['asteroid', 'space body'], ['Arctic', 'northern pole']]
>>> sorted(data, key=lambda pair: pair[0].casefold())
[['Arctic', 'northern pole'], ['asteroid', 'space body'], ['pencil', 'writing implement']]
(Sep-22-2022, 09:21 AM)perfringo Wrote: [ -> ]If you adjust your keyfunc a little bit then you can achieve desired result.

Depending how agressive you would like to be in lowering you can use str.casefold or str.lower.

...and don't use list as a name.

>>> data = [['pencil', 'writing implement'], ['asteroid', 'space body'], ['Arctic', 'northern pole']]
>>> sorted(data, key=lambda pair: pair[0].casefold())
[['Arctic', 'northern pole'], ['asteroid', 'space body'], ['pencil', 'writing implement']]
Thank you so much!