wk1.2

Warm-up

Clean up code via PEP8 and google style guide

  • Following due on Friday at midnight (12am sat):
    • two out of three personal assignments (challenges) from wk0
    • Pair programming assignments for this week (including yesterday's exercises).

Dictionaries

* lists of tuples --> dictionaries 
  • mapping types
    • immutable types to any type (heterogeneous)
  • hashing

Dictionary operations

  • del
  • changing values

Dictionary methods

  • for loops
    • over keys
      • not specifying keys
    • over values
      • convert to list
    • over items
      • convert to list of tuples (look familiar?)
  • the in and not in method for testing membership

Aliasing and copying

>>> opposites = {"up": "down", "right": "wrong", "yes": "no"}
>>> alias = opposites
>>> copy = opposites.copy()  # Shallow copy
>>> alias["right"] = "left"
>>> opposites["right"]
'left'
>>> copy["right"] = "privilege"
>>> opposites["right"]
'left'

Dictionary - exercises

1.

Write a program that reads a string and returns 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 output of the program when the user enters the data “ThiS is String with Upper and lower case Letters”, would look this this:

a  2
c  1
d  1
e  5
g  1
h  2
i  4
l  2
n  2
o  1
p  2
r  4
s  5
t  5
u  1
w  2

2.

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

>>> d = {"apples": 15, "bananas": 35, "grapes": 12}
>>> d["bananas"]
>>> d["oranges"] = 20
>>> len(d)

>>> "grapes" in d

>>> d["pears"]

>>> d.get("pears", 0)

>>> fruits = list(d.keys())
>>> fruits.sort()
>>> print(fruits)

>>> del d["apples"]
>>> "apples" in d

Fill in the body of the function below

def add_fruit(inventory, fruit, quantity=0):
     return

# Make these tests work...
new_inventory = {}
add_fruit(new_inventory, "strawberries", 10)
test("strawberries" in new_inventory)
test(new_inventory["strawberries"] == 10)
add_fruit(new_inventory, "strawberries", 25)
test(new_inventory["strawberries"] == 35)

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:

Word              Count
=======================
a                 631
a-piece           1
abide             1
able              1
about             94
above             3
absence           1
absurd            2

How many times does the word alice occur in the book?

4

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

More on dictionaries

  • in or not in
  • using get to access and update values

A few ways to initialize a dictionary

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e

In [2]:
for a, b in zip(['one', 'two', 'three'],[1, 2, 3]):
    print(a,b)


one 1
two 2
three 3

Looping techniques

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your {0}?  It is {1}.'.format(q, a))

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...

In [ ]: