Pythonlearn 09 Dictionaries
Pythonlearn 09 Dictionaries
Chapter 9
$ python
>>> x = 2
>>> x = 4
>>> print(x)
4
A Story of Two Collections..
• List
• Dictionary
• For now we will just understand them and use them and thank the
creators of Python for making them easy for us
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names :
counts[name] = counts.get(name, 0) + 1
print(counts)
We are surrounded in our daily lives with computers ranging from laptops to cell phones. We
can think of these computers as our “personal assistants” who can take care of many things on
our behalf. The hardware in our current-day computers is essentially built to continuously ask us
the question, “What would you like me to do next?”
Our computers are fast and have vast amounts of memory and could be very helpful to us if we
only knew the language to speak to explain to the computer what we would like it to do next. If
we knew this language we could tell the computer to do tasks on our behalf that were repetitive.
Interestingly, the kinds of things computers can do best are often the kinds of things that we
humans find boring and mind-numbing.
Counting Pattern
counts = dict()
print('Enter a line of text:')
The general pattern to count the
line = input('')
words in a line of text is to split
words = line.split() the line into words, then loop
through the words and use a
print('Words:', words) dictionary to track the count of
print('Counting...')
each word independently.
for word in words:
counts[word] = counts.get(word,0) + 1
print('Counts', counts)
python wordcount.py
Enter a line of text:
the clown ran after the car and the car ran into the tent and the tent fell down on
the clown and the car
Words: ['the', 'clown', 'ran', 'after', 'the', 'car', 'and', 'the', 'car', 'ran', 'into',
'the', 'tent', 'and', 'the', 'tent', 'fell', 'down', 'on', 'the', 'clown', 'and', 'the', 'car']
Counting…
bigcount = None
bigword = None
python words.py
for word,count in counts.items(): Enter file: clown.txt
if bigcount is None or count > bigcount: the 7
bigword = word
bigcount = count
print(bigword, bigcount)
Using two nested loops
Summary
• What is a collection
• Dictionary Constants