I have been comparing the speed of dictionary creation methods in Python.
In the following example, collections.Counter()
and the iterative approaches take the same speed (0.002 secs), whereas the dictionary comprehension method is notably slower (1.115 secs).
I have 2 questions:
1.) Why is the dictionary comprehension slower?
2.) Is there a dictionary comprehension that could match the speed of the other 2 approaches?
s1 = 'string'*10000
# dict comp
d1 = {x:s1.count(x) for x in s1}
# iteration
d1={}
for x in s1:
d1[x] = d1.get(x,0)+1
# Counter
d1 = collections.Counter(s1)