when need count elements of different type , find myself writing like:
if k not in removed: removed[k] = 0 removed[k] = removed[k] + 1
sometimes same thing new empty list grow on time. above code works fine, feels there better way of writing it. there?
in addition defaultdict/counter mentioned in comments, can have default value returned failed get
. allows set initial count 0 if key lookup fails , increment 1, or increment 1 each time key found loop through.
vehicles = ['car', 'bike', 'truck', 'car', 'truck', 'truck'] my_dict = {} k in vehicles: my_dict[k] = my_dict.get(k, 0) + 1
Comments
Post a Comment