MCS 260 Fall 2021
Emily Dumas
In Python, the function max
takes an iterable and returns a largest item in it.
max([2,6,0,2,0,2,1]) # returns 6
max("2775") # returns "7"
max(range(10_000)) # very slow way to get the number 9999
There is also min()
.
Variables changed or created inside a function don't affect anything outside of the function.
Such variables are local to the function.
>>> def f():
... x = 10 # local variable
... print("x is",x)
...
>>> x=3 # danger! same name as local var
>>> f()
x is 10
>>> x
3
def g(x):
x = x + 1
print(x)
a = 5 # global var
g(a) # prints 6
print(a) # prints 5
Equivalent to:
a = 5 # global var
# ---------------------------
x_local_to_g = a
x_local_to_g = x_local_to_g + 1
print(x_local_to_g)
# ---------------------------
print(a)
A dictionary or dict in Python is an unordered collection of key → value pairs.
Dictionaries can be indexed using keys, to get the associated values.
Other languages call this a map or associative array.
Dictionaries in Python are mutable.
Example of syntax for working with dictionaries:
>>> # define a new dict
>>> tuition = { "UIC": 10584, # key "UIC" -> value 10584
... "Stanford": 50703,
... "Harvard": 46340 }
>>> # Get the value associated to a given key
>>> tuition["UIC"]
10584
>>> # Add or change the value at a key
>>> tuition["PSU"] = 18454
>>> tuition
{'UIC': 10584,
'Stanford': 50703,
'Harvard': 46340,
'PSU': 18454}
>>> # Remove a key and value
>>> del tuition["Harvard"]
>>> tuition
{'UIC': 10584, 'Stanford': 50703, 'PSU': 18454}
Mixed types are ok for keys or values.
d = { 1: "fish", "two": "fish", "x": [7,6,5] }
Useful dict methods:
>>> d.values() # All values, without the keys
dict_values(['fish', 'fish', [7, 6, 5]])
>>> d.items() # All key-value pairs (like enumerate(L))
dict_items([(1, 'fish'), ('two', 'fish'), ('x', [7, 6, 5])])
dict_keys, dict_items, dict_values types behave a lot like list, and can be converted to a list with $\texttt{list()}$.
Membership in a dictionary means being a key!
>>> d = { 1: "fish", "two": "fish", "x": [7,6,5] }
>>> "fish" in d
False
>>> 1 in d
True
Forgetting this is a very common source of programming errors.
dicts are iterable, but iterate over the keys.
for k in d: # loop over keys
print(k,"is one of the keys")
for k in d: # loop over keys (index to get value)
print("Key",k,"has value",d[k])
It is common for the values in a dict to be dicts themselves. This is the usual way to make a collection of labeled data indexed by a key.
schooldata = {
"UIC": {
"fullname": "University of Illinois at Chicago",
"tuition": 10584,
"undergrad_students": 21641,
},
"Stanford": {
"fullname": "Leland Stanford Junior University",
"tuition": 50703,
"undergrad_students": 7083
},
"Harvard": {
"fullname": "Harvard University",
"tuition": 46340,
"undergrad_students": 6755
}
}
for shortname,data in schooldata.items():
print(shortname,"has annual tuition",data["tuition"])
pr_replacements = {
"accident": "unplanned event",
"escape": "departure",
"laser-sharks": "fish"
}
original = "an accident involving the escape of laser-sharks"
words = original.split() # [ "an", "accident", ... ]
for w in words:
if w in pr_replacements:
w = pr_replacements[w]
print(w,end=" ")
print()
Output:
an unplanned event involving the departure of fish
Not every type is allowable as a key in a dictionary.
Strings and numeric types are allowed. Lists and dicts are not.
In most cases, allowable keys are immutable types.