# Thinkcspy Chapter 12: Python Dictionaries

Last Updated on February 12, 2024

## Problem 1

Write a program that allows the user to enter a string. It then prints a table of the letters of the alphabet in alphabetical order which occur in the string together with the number of times each letter occurs. Case should be ignored. A sample run of the program might look this this:

Most of the code came from the work I did in labs 1 and 2 of this chapter. The only thing left was to format the printed output in the way that was shown in the instructions above. Below is my final solution for this exercise:

``````# Runestone.Academy thinkcspy course
# Chapter 12
# Problem 1

def countAll(text):
wordDict = {}
text = text.lower()

for char in text:
if char not in wordDict and char.isalpha():
wordDict[char] = text.count(char)

return wordDict

def sortList(text):
wordDict = countAll(text)
alphaList = list(wordDict.items())
alphaList.sort()

return alphaList

def printResult(text):
alphaList = sortList(text)

print("You inputed: " + text)

for char in alphaList:
print(char[0] + ": " + str(char[1]))

printResult(input("What word(s) would you like sorted?"))``````

Result:

## Problem 2

Give the Python interpreter’s response to each of the following from a continuous interpreter session:

Be sure you understand why you get each result. Then apply what you have learned to fill in the body of the function below, and add code for the tests indicated:

At first I didn’t understand what I was being told to do and then I realized that this would be a problem I would need to do outside of the book’s sandboxes. A common theme in this chapter’s labs and exercises.

Below are the results of the prompts as ran in the terminal. In case it’s confusing, `>>>` represent the prompts and the ones without those symbols are the results.

``````>>> d = {'apples': 15, 'bananas': 35, 'grapes': 12}
>>> d['banana']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'banana'
>>> d['oranges'] = 20
>>>
>>> len(d)
4
>>> 'grapes' in d
True
>>> d.get('pears', 0)
0
>>> fruits = d.keys()
>>>
>>> fruits.sort()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict_keys' object has no attribute 'sort'
>>>
>>> print(fruits)
dict_keys(['apples', 'bananas', 'grapes', 'oranges'])
>>> del d['apples']
>>>
>>> 'apples' in d
False
>>> ``````

Now for the code. Here is what they started me with:

``````# Runestone.Academy thinkcspy course
# Chapter 12
# Problem 2

pass

# make these tests work...
new_inventory = {}
#  test that 'strawberries' in new_inventory
#  test that new_inventory['strawberries'] is 10
#  test that new_inventory['strawberries'] is now 35)``````

And here is the final code with my additions:

``````# Runestone.Academy thinkcspy course
# Chapter 12
# Problem 2

if fruit not in inventory:
inventory[fruit] = quantity
else:
inventory[fruit] += quantity

return inventory

# make these tests work...
new_inventory = {}
print(new_inventory)
#  test that 'strawberries' in new_inventory
print(new_inventory.keys())
#  test that new_inventory['strawberries'] is 10
print(new_inventory)
#  test that new_inventory['strawberries'] is now 35)
print(new_inventory)``````

Result:

## The Alice in Wonderland Files

### Problem 3

Write a program called `alice_words.py` that creates a text file named `alice_words.txt` containing an alphabetical listing of all the words, and the number of times each occurs, in the text version of Alice’s Adventures in Wonderland. (You can obtain a free plain text version of the book, along with many others, from http://www.gutenberg.org.) The first 10 lines of your output file should look something like this

How many times does the word, `alice`, occur in the book? If you are writing this in the activecode window simply print out the results rather than write them to a file.

The main challenges I had on this exercise were formatting and exclusively selecting letters. Formatting was a headache, but I got there in the end. The selection process however, wasn’t quite as successful. I got most of the way there, but still ended up with empty strings and asterisks for some reason.

Whatever the issue was, the exercise went well enough for me to want to present it here, so here is the code:

``````# Runestone.Academy thinkcspy course
# Chapter 12
# Problem 3

aliceBook = open("alice_in_wonderland.txt", "r")
aliceDict = {}
outfile = open("alice_words.txt", "w")

for line in aliceBook:
words = line.split()

for word in words:
word = word.lower()
newWord = ""

for char in word:
if char.isalpha():
newWord += char

if newWord != "":
word = newWord

if word not in aliceDict:
aliceDict[word] = 1
else:
aliceDict[word] += 1

aliceList = list(aliceDict.items())
aliceList.sort()

offset = 30 - len("word")
spaces = " " * offset
outfile.write("WORD" + spaces + "COUNT\n" )

for item in aliceList:
offset = 30 - len(item[0])
spaces = " " * offset
outfile.write(item[0] + spaces + str(item[1]) + "\n" )

aliceBook.close()``````

The files are too long to show here, but you can view both the book and output files here

### Problem 4

What is the longest word in Alice in Wonderland? How many characters does it have?

I almost over-complicated this. I was trying to adapt the above code, by creating a new file sorted by the values rather than the keys. Then I realized, I literally just needed to find the max value. So, I got rid of all the output file related stuff and subbed in a block that looked for the longest word. Here is that code:

``````# Runestone.Academy thinkcspy course
# Chapter 12
# Problem 4

aliceBook = open("alice_in_wonderland.txt", "r")
aliceDict = {}

for line in aliceBook:
words = line.split()

for word in words:
word = word.lower()
newWord = ""

for char in word:
if char.isalpha():
newWord += char

if newWord != "":
word = newWord

if word not in aliceDict:
aliceDict[word] = 1
else:
aliceDict[word] += 1

aliceList = list(aliceDict.items())

maxnum = 0
maxWord = ""

for item in aliceList:
if len(item[0]) > maxnum:
maxnum = len(item[0])
maxWord = item[0]

print(maxWord, "-", maxnum)

aliceBook.close()``````

Result:

## Problem 5

Here’s a table of English to Pirate translations

Write a function named `translator` that takes a parameter containing a sentence in English (no punctuation and all words in lowercase) and returns that sentence translated to Pirate.

For example, the sentence “hello there students” should be translated to “avast there swabbies”.

This is what they started me with:

``````# Runestone.Academy thinkcspy course
# Chapter 12
# Problem 5

def translator(english):

pirate = {}
pirate['sir'] = 'matey'
pirate['hotel'] = 'fleabag inn'
pirate['student'] = 'swabbie'
pirate['boy'] = 'matey'
pirate['restaurant'] = 'galley'
pirate['hello'] = 'avast'
pirate['students'] = 'swabbies'

# Complete the function``````

This ended up being more of a challenge than I expected. Mainly due to plurals and exclamation marks. I almost started working on capitalization and the whole “y” to “ies” plural thing, but ended up passing on that for the sake of my mental well-being. I was extra enough on the etch-a-sketch project

Another thing that threw me for a loop was the fact that I needed to add a trailing space when I created `englishList`. I think I ran into that problem either in the strings or lists exercises at some point, but I’m still not clear on what is causing this problem yet. Whatever it is, it was causing the program to omit the last item of the list. The trailing space fixed that. I’ll need to investigate that at some point.

At any rate, here is the final code:

``````# Runestone.Academy thinkcspy course
# Chapter 12
# Problem 5

def translator(english):

pirate = {}
pirate['sir'] = 'matey'
pirate['hotel'] = 'fleabag inn'
pirate['student'] = 'swabbie'
pirate['boy'] = 'matey'
pirate['restaurant'] = 'galley'
pirate['hello'] = 'avast'
pirate['professor'] = 'foul blaggart'
pirate['your'] = 'yer'
pirate['excuse'] = 'arr'
pirate['are'] = 'be'
pirate['lawyer'] = 'foul blaggart'
pirate['the'] = 'th\''
pirate['my'] = 'me'
pirate['is'] = 'be'
pirate['man'] = 'matey'

englishList = english.split() + [' ']

for i in range(len(englishList) - 1):
word = englishList[i]
word = word.lower()
newWord = ""
lengthy = len(newWord) - 1
lengthier = len(word) - 1
lengthiest = len(word) - 2

for char in word:
if char.isalpha():
newWord += char

if newWord[lengthy] == 's':
newWord = newWord[0:lengthy]

if newWord in pirate:
if newWord != word:
if word[lengthier] == 's' or word[lengthiest] == 's':
englishList[i] = pirate[newWord] + 's'

if not word[lengthier].isalpha():
englishList[i] = pirate[newWord] + 's' + word[lengthier]

elif not word[lengthier].isalpha():
englishList[i] = pirate[newWord] + word[lengthier]
else:
englishList[i] = pirate[newWord]

translation = " ".join(englishList)

return translation

print(translator(input("What would you like to say?")))``````

Apparently runtime was too long in the book’s sandbox, so I ran it in my IDE’s terminal. Below is the result. The top line is the input, the bottom is the output.