Want to count values in a Python sequence? Use Counter: Bonus: Counter inherits from dict, getting its methods + operators.
Why use OrderedDict if Python dicts are now ordered? Because equality checks order too:
Make a Python class sortable with __lt__ and __eq__:
By default, str.strip in Python removes leading/trailing whitespace: It takes an optional argument, naming leading/trailing characters to remove. Great for cleaning strings:
Instead of choosing which Python function to run with if/elif/else, use a dispatch table — a dict with functions as values:
Modern Python dicts remember insertion order: This applies in for loops, too!
Using Python defaultdict? Don’t pass a value: Pass a function that returns the default:
Your Python function takes a filename and **kwargs. But this raises an error, since “filename” is passed twice: Solution: Set filename to be positional only: Now any keyword argument works!
Break a Python string into a list of strings with str.split: Limit splits with maxsplit: Or split from the right, with a limit:
Tired of super-long Python Pandas backtraces in Jupyter or IPython? Use the %xmode magic method: %xmode Minimal Now you just see the error, not 50 lines of library internals. You can also set it to Plain, Context, or Verbose.