I have just started learning python and worried that if I use dict.get(key,default_value) or I define my own method for it….so do they have any differences:
[1st method]:
dict={}
for c in string:
if c in dict:
dict[c]+=1
else:
dict[c]=1
and the other dict.get() method that python provides
for c in string:
dict[c]=dict.get(c,0)+1
do they have any differences on efficiency or speed…or they are just the same and 2nd one only saves writing few more lines of code…
For this specific case, use either a
collections.Counter()or acollections.defaultdict()object instead:or
Both are subclasses of the standard
dicttype. TheCountertype adds some more helpful functionality like summing two counters or listing the most common entities that have been counted. Thedefaultdictclass can also be given other default types; usedefaultdict(list)for example to collect things into lists per key.When you want to compare performance of two different approaches, you want to use the
timeitmodule:This shows that using
inis a little faster.There is, however, a third option to consider; catching the
KeyErrorexception:which happens to be the fastest, because only 1 in 10 cases are for a new key.
Last but not least, the two alternatives I proposed:
So the
Counter()type is slowest, butdefaultdictis very fast indeed.Counter()s do a lot more work though, and the extra functionality can bring ease of development and execution speed benefits elsewhere.