Skip to content
All Posts

Python Tips

A set of practical Python examples covering default values, copying, date conversion, iterators, parity, and dictionaries.

Dictionary defaults and deduplication

Use dict.get(key, default) when reading and setdefault when a missing key should also be inserted. dict.fromkeys(sequence, value) is a concise constructor, but a mutable value is shared by every key. A fast way to deduplicate hashable list values is list(set(values)) when order does not matter.

Copying

A slice or list() makes only a shallow list copy. Use copy.deepcopy when nested mutable values must be independent. The same distinction applies to dictionaries.

Dates and times

datetime.date.today() returns today’s date. Convert a date to a datetime with datetime.datetime.combine, and obtain the date portion of a datetime with .date(). datetime.fromtimestamp converts a timestamp in local time. Subtracting two date or datetime values returns a timedelta; milliseconds since the epoch require careful timezone handling.

Small idioms

In Python 2, map returns a list, while iterator-oriented alternatives avoid materializing all values. Test odd numbers with value % 2 != 0 or value & 1. Remove a dictionary key with del mapping[key] when it must exist, or mapping.pop(key, default) when absence is acceptable.


Originally published on SegmentFault.