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 noif key not in dcheck.Countercounts 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))
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner