Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sorting techniques edits #124701

Merged
merged 8 commits into from
Sep 28, 2024
Merged

Conversation

rhettinger
Copy link
Contributor

@rhettinger rhettinger commented Sep 27, 2024

  • Mention other ordering tools that use key-functions (min, max, nsmallest, nlargest).
  • Add a documentation link to str.casefold in case it is unknown to readers.
  • Add tips for handling inputs that aren't directly sortable.

📚 Documentation preview 📚: https://cpython-previews--124701.org.readthedocs.build/


>>> from operator import methodcaller
>>> data = [{'a': 1}, {'b': 2}]
>>> list(map(dict, sorted(map(methodcaller('items'), data))))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not use key= here?

Suggested change
>>> list(map(dict, sorted(map(methodcaller('items'), data))))
>>> sorted(data, key=methodcaller('items'))

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this works. IIRC, an items-view implements set-like comparisons which are a subset/superset tests instead of a total ordering. Also, the intent here was to sort the key/value pairs to so that dicts that compare equal regardless of key ordering will appear side-by-side in the output.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does work here, but it does rely on the set operations and will not work for all dicts. However, that is also true for your version:

>>> data = [{'a': 1}, {'b': 2}, {'a': 3}]
>>> list(map(dict, sorted(map(methodcaller('items'), data))))
[{'a': 1}, {'b': 2}, {'a': 3}]
>>> sorted(data, key=methodcaller('items'))
[{'a': 1}, {'b': 2}, {'a': 3}]

To work correctly, we need to sort the itemsviews:

>>> sorted(data, key=lambda d: sorted(d.items()))
[{'a': 1}, {'a': 3}, {'b': 2}]

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes sense.

Doc/howto/sorting.rst Show resolved Hide resolved
Doc/howto/sorting.rst Outdated Show resolved Hide resolved
@rhettinger rhettinger merged commit 165ed68 into python:main Sep 28, 2024
24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs Documentation in the Doc dir skip issue skip news sprint
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

3 participants