A common use of dictionaries is to count the occurrences of like items in a sequence; a typical example is counting the occurrences of words in a body of text. The following code creates a dictionary where each word in the text is used as a key and the number of occurrences as its value. This uses a very common idiom of nested loops. Here we are using it to traverse the lines in a file in an outer loop and the keys of a dictionary on the inner loop:
def wordcount(fname): try: fhand=open(fname) except: print('File can not be opened') exit() count=dict() for line in fhand: words=line.split() for word in words: if word not in count: count[word]=1 else: count[word]+=1 return(count)
This will return ...