




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





Today
Homework
For homework 12: Need to take a line of text and separate into words
The Python split() function:
line = "spam ham eggs"
words = line.split()
words
[โspamโ, โhamโ, โeggsโ]
Every key is unique in a dictionary
d = {โaโ: 1, โbโ: 2, โaโ: 3}
d {โaโ: 3, โbโ: 2}
Dictionaries support many of the same operations as lists
d = {โaโ: 1, โbโ: 2, โcโ: 3}
d[โaโ] # subscript 1
d[โdโ] = 1 # add a key-value pair d {โaโ: 1, โbโ: 2, โcโ: 3, โdโ: 1}
d[โaโ] = 2 # set a key value d {โaโ: 2, โbโ: 2, โcโ: 3, โdโ: 1}
d.get(โaโ) 2
d.get(โeโ, 0) # alt value 0
โaโ in d # key in dictionary True
โeโ in d False
โeโ not in d True
The keys() function returns a sequence of keys
d = {โaโ: 1, โbโ: 1, โcโ: 1}
for key in d.keys(): # same as: for key in d: print(key)
The values() function returns a sequence of values
for val in d.values(): print(val)
The items() function returns a sequence of (key,val) tuples
for key, val in d.items(): print(key, "=", val)
The copy() function copies a dictionary
d0 = d.copy() d
words [โspamโ, โhamโ, โeggsโ] - Creates a list of strings based on a separator - By default, any whitespace character (e.g., space, newline, tab) - Can also give a separator, e.g., line.split(โ,โ) ## Dictionaries Every key is unique in a dictionary - For example: >>> d = {โaโ: 1, โbโ: 2, โaโ: 3} >>> d {โaโ: 3, โbโ: 2} - Note the + operator is not supported ## Dictionary operations Dictionaries support many of the same operations as lists >>> d = {โaโ: 1, โbโ: 2, โcโ: 3} >>> d[โaโ] # subscript 1 >>> d[โdโ] = 1 # add a key-value pair >>> d {โaโ: 1, โbโ: 2, โcโ: 3, โdโ: 1} >>> d[โaโ] = 2 # set a key value >>> d {โaโ: 2, โbโ: 2, โcโ: 3, โdโ: 1} >>> d.get(โaโ) 2 >>> d.get(โeโ, 0) # alt value 0 >>> โaโ in d # key in dictionary True >>> โeโ in d False >>> โeโ not in d True ## Dictionaries and iteration The keys() function returns a sequence of keys d = {โaโ: 1, โbโ: 1, โcโ: 1} for key in d.keys(): # same as: for key in d: print(key) - Prints: a b c The values() function returns a sequence of values for val in d.values(): print(val) - Prints: 1 1 1 The items() function returns a sequence of (key,val) tuples for key, val in d.items(): print(key, "=", val) - Prints: a = 1 b = 1 c = 1 The copy() function copies a dictionary >>> d0 = d.copy() >>> d {โaโ: 1, โbโ: 1, โcโ: 1}
d0[โaโ] = 2
d {โaโ: 2, โbโ: 1, โcโ: 1}
d {โaโ: 1, โbโ: 1, โcโ: 1}
The len() function returns the length of a dictionary
len(d) 3