I’m working through exercises in Building Skills in Python, which to my knowledge don’t have any published solutions.
In any case, I’m attempting to have a dictionary count the number of occurrences of a certain number in the original list, before duplicates are removed. For some reason, despite a number of variations on the theme below, I cant seem to increment the value for each of the ‘keys’ in the dictionary.
How could I code this with dictionaries?
dv = list()
# arbitrary sequence of numbers
seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2]
# dictionary counting number of occurances
seqDic = { }
for v in seq:
i = 1
dv.append(v)
for i in range(len(dv)-1):
if dv[i] == v:
del dv[-1]
seqDic.setdefault(v)
currentCount = seqDic[v]
currentCount += 1
print currentCount # debug
seqDic[v]=currentCount
print "orig:", seq
print "new: ", dv
print seqDic
defaultdictis notdict(it’s a subclass, and may do too much of the work for you to help you learn via this exercise), so here’s a simple way to do it with plaindict:this simple approach works particularly well here because you need the
if i in seqDictest anyway for the purpose of buildingdvas well asseqDic. Otherwise, simpler would be:using the handy method
getofdict, which returns the second argument if the first is not a key in the dictionary. If you like this idea, here’s a solution that also buildsdv:Edit: If you don’t case about the order of items in
dv(rather than wantingdvto be in the same order as the first occurrence of item inseq), then just using (after the simple version of the loop)also works (in Python 2, where
.keysreturns a list), and so doeswhich is fine in both Python 2 and Python 3. Under the same hypothesis (that you don’t care about the order of items in
dv) there are also other good solutions, such ashere, we first use the
fromkeysclass method of dictionaries to build a new dict which already has0as the value corresponding to each key, so we can then just increment each entry without such precautions as.getor membership checks.