Skip to content

Possible usage of itemgetter(key) #26

Description

@filak

Thank you for a great library!

I would like to sort a list of dicts by multiple values - some possibly in Unicode - sample program:

from pyuca import Collator
from operator import itemgetter
coll = Collator()

def multisort_list_of_dicts(xs, specs):
    for key, reverse, col in reversed(specs):   
        if col:
            xs.sort(key=coll.sort_key(itemgetter(key)), reverse=reverse)
        else:    
            xs.sort(key=itemgetter(key), reverse=reverse)
    return xs

data = [{'k1': 'd', 'k2': 10},{'k1': 'č', 'k2': 10},{'k1': 'a', 'k2': 20},{'k1': 'a', 'k2': 10}]

Standard sorting:

sort_spec = (('k2', False, False), ('k1', False, False))

for item in multisort_list_of_dicts(data, sort_spec):
    print(item)
  • works as expected - with the accented chars shifted after normal chars:
{'k1': 'a', 'k2': 10}
{'k1': 'd', 'k2': 10}
{'k1': 'č', 'k2': 10}
{'k1': 'a', 'k2': 20}

Unicode sorting for k1:

sort_spec = (('k2', False, False), ('k1', False, True))

for item in multisort_list_of_dicts(data, sort_spec):
    print(item)
  • this obviously cannot work, because sort_key() expects a string:

    def sort_key(self, string):

  File "C:\Programs\Python\Python311\Lib\site-packages\pyuca\collator.py", line 119, in sort_key
    normalized_string = unicodedata.normalize("NFD", string)
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: normalize() argument 2 must be str, not operator.itemgetter

How to get the desired output with pyuca ?

{'k1': 'a', 'k2': 10}
{'k1': 'č', 'k2': 10}
{'k1': 'd', 'k2': 10}
{'k1': 'a', 'k2': 20}

How to possibly handle the itemgetter input in pyuca ?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions