Intro to
Programming
(with Python)

Fall 2018
course
site

Tue Nov 6

Aside : fifty fizzbuzzes discussion

Discuss the homework. I've posted some examples.

This week : data structures (chap 11). Please read it.

dictionaries

Python "dictionary" data structure. Like an array, but with non-numeric "keys". The pairs of things in 'em are called (key, value) pairs. And there are lots of tricky methods built in.

jim = { "name" : "Jim", "age": 53 }
print("My name is ", jim['name'])
print("My age is ", jim['age']
# Look at dir(jim) to see all the methods like
#   jim.keys()
#   jim.items()
#   jim.has_key(key)
#   jim.get(key, value_otherwise)

Dictionaries are very useful data structures. In fact, the symbol table of a running program is essentially just a dictionary, with each variable's name and value. Objects are very like dictionaries, with "slots" for both data and methods. Most of the other CS data structures are things with specific uses built from lists and dictionaries.

(Discuss javascript objects and dictionaries ...)

Dictionaries are sometimes called "hash tables" or just "hashes" ... discuss why.

How are dictionaries and objects similar? Different?

The "name spaces" that we've been seeing, a list of variables and values that we keep track of when a function runs ... those are just essentially a dictionary.

Be clear that dictionaries are unordered ... what does that mean? Can we sort a dictionary?

One thing dictionaries are good for is counting things, using key:count for each sort of thing.

Example: counting how many times each word appears in a file.

The task is to write a program which will read in a file which has one word per line, and then to report how many times each word was seen.

A sample words.txt file is attached. Here's the start of the program :

"""
 count_words.py

 Read words.txt which has one word per line.
 Count how many times each word appears
 and print a summary.

   $ python count_words.py
   -- count_words --
     12 cat          
      2 dog          
      2 duck         
      1 elephant     
      3 mouse        
"""

def main():
    print '-- count_words --'

if __name__ == '__main__':
    import doctest
    doctest.testmod()
    main()

And here's the corresponding words.txt file like.

cat
dog
elephant
cat
cat
mouse
mouse
duck
mouse
duck
dog

data structures

We now have these sorts of things which can store information :

These can be embedded within each other to create all sorts of containers for various kinds of information, depending on its internal structure.

Can you think of an example of

https://cs.marlboro.college /cours /fall2018 /python /notes /data
last modified Sat April 20 2024 12:17 pm