One common use of dictionaries is counting how often we “see” something
>>> ccc = dict()
>>> ccc['csev'] = 1
>>> ccc['cwen'] = 1
>>> print(ccc)
{'csev': 1, 'cwen': 1}
>>> ccc['cwen'] = ccc['cwen'] + 1
>>> print(ccc)
{'csev': 1, 'cwen': 2}
>>> ccc = dict()
>>> print(ccc['csev'])
KeyError: 'csev'
When we encounter a new name, we need to add a new entry in the dictionary and if this the second or later time we have seen the name, we simply add one to the count in the dictionary under that name
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names:
if name not in counts :
counts[name] = 1
else :
counts[name] = counts[name] + 1
print(counts)
The pattern of checking to see if a key is already in a dictionary and assuming a default value if the key is not there is so common that there is a method called get() that does this for us
Default value if they does not exist (and no Traceback).
if name in counts:
x = counts[name]
else :
x = 0
x = counts.get(name, 0)
{'csev': 2, 'zqian': 1, 'cwen': 2}
We can use get() and provide a default value of zero when the key is not yet in the dictionary - and then just add one
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names:
counts[name] = counts.get(name, 0) + 1
print(counts)
The general pattern to count the words in a line of text is to split the line into words, then loop through the words and use a dictionary to track the count of each word independently.
counts = dict()
print('Enter a line of text: ')
line = input('')
words = line.split()
print('Words:', words)
print('Counting...')
for word in words:
counts[word] = counts.get(word, 0) + 1
print('Counts', counts)
Even though dictionaries are not stored in order, we can write a for loop that goes through all the entries in a dictionary - actually it goes through all of the keys in the dictionary and looks up the values
You can get a list of keys, values, or items(both) from a dictionary
jjj = {'chuck' : 1, 'fred' : 42, 'jan' : 100}
for aaa.bbb in jjj.items() :
print(aaa, bbb)
name = input('Enter file:')
handle = open(name)
counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word,0) + 1
bigcount = None
bigword = None
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print(bigword, bigcount)