Dictionaries

Why Use collections.OrderedDict?

  • While dicts in Python 3.6+ have ordering built-in, it might be useful to use OrderedDict to signal importance of ordering
  • You can performed reversed on it
  • It has a .move_to_end method to move a key to the front or end of the dict
  • It has a .popitem method to pop the first or last item in the dict

Why Use collections.ChainMap?

  • It stores dicts by reference, thereby making ChainMap updatable
  • It allows for prioritization of values from leftmost dict to rightmost dict. This might be practical for argument parsing:
ChainMap(cli_args, os.environ, app_defaults)
  • You still want to maintain the underlying dictionaries
  • Combining / updating dictionaries are expensive

Why Use types.MappingProxyType

  • Creates a read-only view to a dict, since it’s only a proxy. This means you don’t need to copy your dict.
    • However, it only works on the first level, so nested dictionary members are mutable
  • Consider using frozendict as well

Lists

Why Use array.array?

  • More space-efficient
  • Enforces member data type

Note

When working with bytestrings, this data structure assumes your platform’s byte order.

To swap the byte order, use the .byteswap method.
Alternatively, use bytearray for more granular control.


Structs

Why Use collections.namedtuple?

  • Enforces the fields
  • Allows for name-based indexing like dicts
  • Has the memory efficiency and immutability of tuples
  • However, it is not type-checked

Why Use typing.NamedTuple?

  • Same as collections.namedtuple but with type hint support1

Sets

Why Use frozenset?

  • It’s immutable upon creation
  • Immutability means that is can be used as a dictionary key!

References

https://realpython.com/python-data-structures/#typingnamedtuple-improved-namedtuples

Footnotes

  1. Actually, Brett Cannon makes a case of not returning NamedTuples in your API. ↩