Interview Prep/Python for DevOps/Language essentials & functions

What do `collections.defaultdict`, `Counter` and `namedtuple` give you?

IntermediateConceptLanguage essentials & functions
Answer
  • defaultdict(list) creates a default value on first access, so grouping needs no if key not in d check.
  • Counter counts hashable items and has .most_common(n).
  • namedtuple (or better, typing.NamedTuple / dataclass) gives tuples readable field names.
from collections import Counter, defaultdict
by_type = defaultdict(list)
for i in instances:
    by_type[i["InstanceType"]].append(i["InstanceId"])
status_counts = Counter(line.split()[8] for line in open("access.log"))
print(status_counts.most_common(5))
All Python for DevOps questions Roadmap: Python for automation

More on Language essentials & functions