Data Structures

Dictionary Tricks

Sorting Dictionary Python dictionaries don’t have an inherent order. You can iterate over them just fine but there’s no guarantee that iteration returns the dictionary’s elements in any particular order。

2023-02-04

Priority Queues

TL;DR queue.PriorityQueue stands out from the pack with a nice object-oriented interface and a name that clearly states its in- tent. It should be your preferred choice. If you’d like to avoid the locking overhead of queue.

2023-01-08

Queues

TL;DR collections.deque is an excellent default choice for implementing a FIFO queue data structure in Python list objects can be used as queues, but this is generally NOT recommended due to slow performance.

2023-01-08

Stacks

TL;DR collections.deque provides a safe and fast general-purpose stack implementation. First choice! The built-in list type can be used as a stack, but be careful to only append and remove items with append() and pop() in order to avoid slow performance.

2023-01-08

Sets

TL;DR Use the built-in set type when looking for a mutable set. frozenset objects are hashable and can be used as dictionary or set keys. collections.Counter implements multiset or “bag” data structures.

2023-01-07

Records, Structs, and Data Transfer Objects

TL;DR You only have a few (2-3) fields →\rightarrow Using a plain tuple object may be okay if the field order is easy to remember or field names are superfluous. You need immutable fields →\rightarrow plain tuples, collections.

2023-01-05

Array Data Structure

TL;DR You need to store arbitrary objects, potentially with mixed data types? →\rightarrow Use list (mutable) or tuple (immutable) You have numeric (integer or floating point) data and tight packing and performance is important?

2023-01-04

Dictionaries, Maps, and Hashtables

TL;DR Dictionaries are the central data structure in Python THe built-in dict type is “good enough” most of the time Specialized implementations, like read-only or ordered dicts, are also available in the Python standard library.

2022-12-19