CS 22A Summary Ch11 PDF

Title CS 22A Summary Ch11
Course Python Programming for Non-Majors 1
Institution San José State University
Pages 3
File Size 93.9 KB
File Type PDF
Total Downloads 70
Total Views 141

Summary

Summary based on lecture and textbook for chapter 11...


Description

CS 22A Summary Ch11 Dictionaries 1. A set of counters a. A dictionary is like a list, but more general b. A set of keys and a set of values. c. Each key maps to a value. d. The association of a key and a value is called a key-value pair or sometimes an item. e. Example: def histogram(s): d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] += 1 return d 2. Looping and dictionaries a. If you use a dictionary in a for statement, it traverses the keys of the dictionary b. Example: def print_hist(h): for c in h: print c, h[c] Here’s what the output looks like: h = histogram('parrot') print_hist(h) a1 p1 r2 t1 o1 3. Reverse lookup a. Given a dictionary d and a key k, it is easy to find the corresponding value v = d[k] b. Example: def reverse_lookup(d, v): for k in d: if d[k] == v: return k raise ValueError 4. Dictionaries and lists

a. Lists can appear as values in a dictionary. b. Example: def invert_dict(d): inv = dict() for key in d: val = d[key] if val not in inv: inv[val] = [key] else: inv[val].append(key) return inv

5. Memos

a. 6. Global variables a. Variables in __main__ are sometimes called global because they can be accessed from any function b. It is common to use global variables for flags

7. Long integers a. Values with type int have a limited range; long integers can be arbitrarily big, but as they get bigger they consume more space and time. b. The mathematical operators work on long integers, and the functions in the math module, too, so in general any code that works with int will also work with long....


Similar Free PDFs