How do I initialize a Counter from a list of key/initial counts pairs?
counter, data-structures, python, python-3.x, python-internals
Solution
I would just do a loop:
for obj, cnt in [ ('a', 1), ('b', 2) ]:
counter[obj] = cnt
You could also just call the parent `dict.update` method:
>>> from collections import Counter
>>> data = [ ('a', 1), ('b', 2) ]
>>> c = Counter()
>>> dict.update(c, data)
>>> c
Counter({'b': 2, 'a': 1})
Lastly, there isn't anything wrong with your original solution:
Counter(dict(list_of_pairs))
The expensive part of creating dictionaries or counters is hashing all of the keys and doing periodic resizes. Once the dictionary is made, converting it to a Counter is very cheap about as fast as a dict.copy(). The hash values are reused and the final Counter hash table is pre-sized (no need for resizing).
Problem
If I have a sequence of `(key, value)` pairs, I can quickly initialize a dictionary like this: ``` >>> data = [ ('a', 1), ('b', 2) ] >>> dict(data) {'a': 1, 'b': 2} ``` I would like to do the same with a `Counter` dictionary; but how? Both the constructor and the `update()` method treat the ordered pairs as keys, not key-value pairs: ``` >>> from collections import Counter >>> Counter(data) Counter({('a', 1): 1, ('b', 2): 1}) ``` The best I could manage was to use a temporary dictionary, which is ugly and needlessly circuitous: ``` >>> Counter(dict(data)) Counter({'b': 2, 'a': 1}) ``` Is there a proper way to directly initialize a `Counter` from a list of `(key, count)` pairs? My use case involves reading lots of saved counts from files (with unique keys).