Adding an Entry in to Dictionary–4.10
There are many ways to add an entry in to dict. There are 4 methods cited in this recipe
import itertools
def addword1(theIndex, word, pagenumber):
theIndex.setdefault(word,\[\]).append(pagenumber)
def addword2(theIndex, word, pagenumber):
if word in theIndex :
theIndex.setdefault(word,\[\]).append(pagenumber)
else :
theIndex\[word\] = \[pagenumber\]
def addword3(theIndex, word, pagenumber):
if word in theIndex :
theIndex.setdefault(word,\[\]).append(pagenumber)
else :
theIndex\[word\] = \[pagenumber\]
def addword4(theIndex, word, pagenumber):
theIndex\[word\] = theIndex.get(word,\[\]) +\[pagenumber\]
Out of all the methods, addword1 is the most efficient and addword4 is the least efficient as you are constructing 3 lists for even loop run