-
-
Notifications
You must be signed in to change notification settings - Fork 32k
Sorting techniques edits #124701
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
Conversation
Doc/howto/sorting.rst
Outdated
|
||
>>> from operator import methodcaller | ||
>>> data = [{'a': 1}, {'b': 2}] | ||
>>> list(map(dict, sorted(map(methodcaller('items'), data)))) |
There was a problem hiding this comment.
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?
>>> list(map(dict, sorted(map(methodcaller('items'), data)))) | |
>>> sorted(data, key=methodcaller('items')) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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}]
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That makes sense.
str.casefold
in case it is unknown to readers.📚 Documentation preview 📚: https://cpython-previews--124701.org.readthedocs.build/