So I would like to natural sort the dictionary, here is my first try on doing so:
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
x = dict(sorted(ops.items(),key=alphanum_key))
print x
Error:
line 394, in <lambda$14479>
TypeError: expected string for parameter 'string' but got 'tuple'
Would really appreciate any help for sorting the groups any better
Kind Regards.
Well first of all, pythons built-in dictionaries cannot be sorted. They are inherently an unordered collection. If you want an ordered and sortable dict you can try the OrderedDict from the collections modules, but I don’t think sort and sorted work the same way with OrderedDict. Meaning the sorting method may be more complicated.
Also by python best practices you should define a function instead of assigning a lambda expression. lambda should only be used for in-lining something.
I looked at the code you pointed out some stuff that may be wrong or a little weird, but I don’t have your full code so I’m not sure how accurate it is.
convert = lambda text: int(text) if text.isdigit() else text.lower()
# key in this lambda function looks like it is receiving a tuple and causing an error
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
# dict cannot be sorted, so converting to dict invalidates the sorting
# also key is sorting based on a list from alphanum_key. I'm not sure if that is your intention.
x = dict(sorted(ops.items(),key=alphanum_key))
print x
I have read a few articles about sorting dictionaries but still don´t get it.
But I can say that the sorted() method gives me a sorted dictionary that has not the same order than before. And this is also the result that I can see in the userinterface. So I don´t get why sorting should not be possible.
Here´s what ChatGPT suggests:
import re
def natural_sort_key(s):
return [int(c) if c.isdigit() else c.lower() for c in re.split('(\d+)', s)]
def _prepare_context(self):
if isinstance(self._context, dict) and self._context.keys():
self._update_ctx_groups(sorted(self._context.keys(), key=natural_sort_key))
new_ctx = {}
for ctx_grp, ctx_items in self._context.items():
new_ctx[ctx_grp] = self._prepare_context_items(ctx_items)
self._context = new_ctx
else:
self._context = self._prepare_context_items(self._context)
I will do so @Jean-Marc
I think the best would be to just remove the sorted() method from the forms.SelectFromList so everyone can sort the groups like desired before calling the form.
The items (sheets) themselfes dont get a sorting from the form, so why do the groups need one.