Text
stringlengths
1
9.41k
print(f"Key: '{key}', value: {value}") ... Key: 'living room', value: ['armchair', 'sofa', 'table'] Key: 'bedroom', value: ['bed', 'nightstand', 'dresser'] Key: 'office', value: ['desk', 'chair', 'cabinet'] Some examples ``` Let’s say we wanted to count the number of pieces of furniture in our dwelling. ``` ...
count = count + len(lst) ... >>> count 9 ``` Let’s say we wanted to find all the students in the class who are not CS majors, assuming the items in our dictionary look like this: ``` >>> students = ...
{'esmerelda' : {'class': 2024, 'major': 'ENSC', 'gpa': 3.08}, ... 'winston': {'class': 2023, 'major': 'CS', 'gpa': 3.30}, ... 'clark': {'class': 2022, 'major': 'PHYS', 'gpa': 2.95}, ...
'kumiko': {'class': 2023, 'major': 'CS', 'gpa': 3.29}, ...
'abeba' : {'class': 2024, 'major': 'MATH', 'gpa': 3.71}} ``` One approach: ``` >>> non_cs_majors = [] >>> for student, info in students.items(): ... if info['major'] != 'CS': ...
non_cs_majors.append(student) ... >>> non_cs_majors ['esmerelda', 'clark', 'abeba'] ###### 16.3 Deleting dictionary keys ``` Earlier we saw that we could use list’s .pop() method to remove an element from a list, removing either the last element in the list (the default, when no argument is supplied), or at a s...
The .pop() method for dictionaries requires a valid key as an argument.
This is because dictionaries don’t have the same sense of linear order as a list—everything is based on keys. So this works: ``` >>> d = {'foo': 'bar'} >>> d.pop('foo') 'bar' ``` but this does not: ``` >>> d = {'foo': 'bar'} >>> d.pop() Traceback (most recent call last): File "<stdin>", line 1, in <modu...
'oswald': 'goldfish', 'wyatt': 'ferret'} >>> del pets['oswald'] # RIP oswald :( >>> pets {'fluffy': 'gerbil', 'george': 'turtle', 'wyatt': 'ferret'} ``` But be careful!
If you do not specify a key, the entire dictionary will be deleted! ``` >>> pets = {'fluffy': 'gerbil', 'george' : 'turtle', ...
'oswald': 'goldfish', 'wyatt': 'ferret'} >>> del pets # oops! >>> pets Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'pets' is not defined ``` Notice also that .pop() with a key supplied will return the value associated with that key and then remove the key/value pai...
del will simply delete the entry. ###### 16.4 Hashables The keys of a dictionary cannot be arbitrary Python objects.
In order to serve as a key, an object must be hashable. Without delving into too much technical detail, the reason is fairly straightforward.
We can’t have keys that might change! ----- Imagine if that dictionary or thesaurus on your desk had magical keys that could change. You’d never be able to find anything.
Accordingly, all keys in a dictionary must be hashable—and not subject to possible change. Hashing is a process whereby we calculate a number (called a hash) from an object.
In order to serve as a dictionary key, this hash value must never change. What kinds of objects are hashable?
Actually most of the objects we’ve seen so far are hashable. Anything that is immutable and is not a container is hashable. This includes int, float, bool, str.
It even includes objects of type range (though it would be very peculiar indeed if someone were to use a range as a dictionary key). What about things that are immutable and are containers?
Here we’re speaking of tuples. If all the elements of a tuple are themselves immutable, then the tuple is hashable.
If a tuple contains a mutable object, say, a list, then it is not hashable. We can inspect the hash values of various objects using the built-in function, hash(). ``` >>> x = 2 >>> hash(x) 2 >>> x = 4.11 >>> hash(x) 253642731013507076 >>> x = 'hello' >>> hash(x) 1222179648610370860 >>> x = True >>...
All it takes is one mutable element, no matter how deeply nested, to make an object unhashable. ``` >>> x = (1, 2, (3, 4, (5, 6, (7, 8, [9])))) >>> hash(x) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' ``` Finally, it should go without saying that ...
It’s common enough in many word guessing and related games that we’d want this information. Let’s say we have this string: “How far that little candle throws its beams!
So shines a good deed in a naughty world.”[2] How would we count all the symbols in this? Certainly, separate variables would be cumbersome. Let’s use a dictionary instead.
The keys in the dictionary are the individual letters and symbols in the string, and the values will be their counts.
To simplify things a little, we’ll convert the string to lower case before counting. 2William Shakespeare, The Merchant of Venice, Act V, Scene I (Portia). ----- ``` s = "How far that little candle throws its beams!
" \ "So shines a good deed in a naughty world." d = {} for char in s.lower(): try: d[char] += 1 except KeyError: d[char] = 1 ``` We start with an empty dictionary.
Then for every character in the string, we try to increment the value associated with the dictionary key. If we get a KeyError, this means we haven’t seen that character yet, and so we add a new key to the dictionary with a value of one.
After this code has run, the dictionary, d, is as follows: ``` {'h': 5, 'o': 6, 'w': 3, ' ': 16, 'f': 1, 'a': 7, 'r': 3, 't': 7, 'l': 4, 'i': 4, 'e': 6, 'c': 1, 'n': 4, 'd': 5, 's': 6, 'b': 1, 'm': 1, '!': 1, 'g': 2, 'u': 1, 'y': 1, '.': 1} ``` So we have five ‘h’, six ‘o’, three ‘w’, and so on. We could wr...
This is similar to the IndexError you’ve seen in the cases of lists and tuples. If you encounter a KeyError it means the specified key does not exist in the dictionary. ----- ``` >>> furniture = {'living room': ['armchair', 'sofa', 'table'], ...
'bedroom': ['bed', 'nightstand', 'dresser'], ...
'office': ['desk', 'chair', 'cabinet']} >>> furniture['kitchen'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'kitchen' TypeError ``` If you try to add to a dictionary a key which is not hashable, Python will raise a type error: ``` >>> d = {[1, 2, 3]: 'cheese'} Traceba...
This will depend on context. ###### 16.7 Exercises **Exercise 01** Create a dictionary for the following data: Student NetID Major Courses Porcupine, Egbert eporcupi CS CS1210, CS1080, MATH2055, ANTH1100 Pickle, Edwina epickle BIOL BIOL1450, BIOL1070, MATH2248, CHEM1150 Quux, Winston wquux ARTS ARTS2100, ARTS275...
What do you think should serve as keys for the dictionary? b.
Should you use a nested dictionary? c .What are the types for student, netid, major, and courses? ----- **Exercise 02** Now that you’ve created the dictionary in Exercise 01, write queries for the following.
A query retrieves selected data from some data structure. Here the data structure is the dictionary created in exercise 01. Some queries may be one-liners. Some queries may require a loop. 1.
Get Winston Quux’s major. 2. If you used NetID as a key, then write a query to get the name associated with the NetID epickle.
If you used something else as a key, then write a query to get Edwina Pickle’s NetID. 3. Construct a list of all students taking CS1210. **Exercise 03** Dictionary keys must be unique.
We cannot have duplicate keys in a dictionary. What do you think happens if we were to enter this into the Python shell? ``` d = {'foo': 'bar', 'foo': 'baz'} ``` What do you think is the value of d?
Guess first, then check! **Exercise 04** Create this dictionary: ``` d = {'foo': 'bar'} ``` Now pass d as an argument to a function which has a single formal parameter, d_ Within the function modify the dictionary (mutate it), but return None (how you modify it is up to you).
What happens to d in the outer scope? Note: Don’t assign a new value to d_.
Just mutate it by adding a key, removing a key, changing a value, etc. **Exercise 05** Write a function that takes a string as an argument and returns a dictionary containing the number of occurrences of each character in the string. **Exercise 06** a.
Write a function that takes an arbitrary dictionary and returns the keys of the dictionary as a list. b.
Write a function that takes an arbitrary dictionary and returns the values of the dictionary as a list. ----- #### Chapter 17 ### Graphs We have looked at the dictionary data structure, which associates keys with values, and we’ve looked at some examples and use cases.
Now that we understand dictionaries, we’re going to dive into graphs. Graphs are a collection of vertices (nodes) connected by edges, that represent relationships between the vertices (nodes).
We’ll see that a dictionary can be used to represent a graph. **Learning objectives** - You will learn some of the terms associated with graphs. - You will learn how to represent data using a graph. - You will learn about searching a graph using breadth-first search. **Terms introduced** - graph - verti...
They can be used to represent game states, positions on a map with routes, people in a social network, and so on.
Here we will consider graphs that represent positions on a map with routes and that represent friendships in a social network. Let’s start with maps.
Consider a minimal example of two towns in Michigan, Ann Arbor and Ypsilanti. Here, in the language of graphs, we have two vertices (a.k.a., nodes) representing the towns, Ann Arbor and Ypsilanti, and an edge connecting the vertices, indicating that a route exists between them.
We can travel 319 ----- along this route from Ann Arbor to Ypsilanti, and from Ypsilanti to Ann Arbor. Notice the symmetry.
This is because the edge between Ann Arbor and Ypsilanti is undirected, which is reasonable, since the highway that connects them allows traffic in both directions.[1] We refer to vertices which share a common edge as neighbors.
We also refer to vertices which share a common edge as adjacent. So in the example above, Ann Arbor and Ypsilanti are neighbors.
Ann Arbor is adjacent to Ypsilanti, and Ypsilanti is adjacent to Ann Arbor. Here’s a little more elaborate example: In this example, Burlington is adjacent to St Albans, Montpelier and Middlebury.
Rutland is adjacent to Middlebury and Bennington.
(Yes, we’re leaving out a lot of detail for simplicity’s sake.) So the question arises: how do we represent a graph in our code? There are several ways, but what we’ll demonstrate here is what’s called the adjacency list representation. We’ll use a dictionary, with town names as keys and the values will be a list of al...
This is called a cycle. If a graph doesn’t have any cycles, it is called an acyclic graph. Similarly, if a graph contains at least one cycle, then it is called a cyclic graph.
So, this is a cyclic graph. ###### 17.2 Searching a graph: breadth-first search It is often the case that we wish to search such a structure.
A common approach is to use what is called breadth-first search (BFS).
Here’s how it works (in the current context): We keep a list of towns that we’ve visited, and we keep a queue of towns yet to visit.
Both the list of towns and the queue are of type list. We choose a starting point (here it doesn’t matter which one), and we add it to the list of visited towns, and to the queue.
This is how we begin. Then, in a while loop, as long as there are elements in the queue: - pop a town from the front of the queue - for each neighboring town, if we haven’t already visited the town: **– we append the neighboring town to the list of visited towns** **– we append the neighboring town to the back o...
So this algorithm will terminate. Once the algorithm has terminated, we have a list of the visited towns, in the order they were visited. Needless to say, this isn’t a very sophisticated approach.
For example, we don’t consider the distances traveled, and we have a very simple graph. But this suffices for a demonstration of BFS. ----- ###### A worked example Here’s a complete, worked example of breadth-first search.
It might help for you to go over this while checking the map (above). Say we choose St Johnsbury as a starting point.
Thus, the list of visited towns will be St Johnsbury, and the queue will contain only St Johnsbury.
Then, in a while loop… First, we pop St Johnsbury from the front of the queue, and we check its neighbors.
Its neighbors are Montpelier, Newport, and White River Junction so we append Montpelier, Newport, and White River Junction to the list of visited towns, and to the queue.
At this point, the queue looks like this: ``` ['Montpelier', 'Newport', 'White River Junction'] ``` At the next iteration, we pop Montpelier from the front of the queue. Now, when we check Montpelier’s neighbors, we find Burlington, White River Junction, and St Johnsbury.
St Johnsbury has already been visited and so has White River Junction, so we leave them be. However, we have not visited Burlington, so we append it to the list of visited towns and to the queue.
At this point, the queue looks like this: ``` ['Newport', 'White River Junction', 'Burlington'] ``` At the next iteration, we pop Newport from the front of the queue. We check Newport’s neighbors and find only St Johnsbury, so there’s nothing to append to the queue.
At this point, the queue looks like this: ``` ['White River Junction', 'Burlington'] ``` At the next iteration we pop White River Junction from the front of the queue.
White River Junction is adjacent to Montpelier (already visited), Brattleboro, and St Johnsbury (already visited). So we append Brattleboro to visited list and to the queue.
At this point, the queue looks like this: ``` ['Burlington', 'Brattleboro'] ``` At the next iteration, Burlington is popped from the queue.
Now we check Burlington’s neighbors, and we find St Albans, Montpelier (already visited), and Middlebury.
Montpelier we’ve already visited, but St Albans and Middlebury haven’t been visited yet, so we append them to the list of visited towns and to the queue.
At this point, the queue looks like this: ``` ['Brattleboro', 'St Albans', 'Middlebury'] ``` At the next iteration, Brattleboro is popped from the front of the queue.
Brattleboro is adjacent to White River Junction (already visited). At this point, the queue looks like this: ----- ``` ['St Albans', 'Middlebury'] ``` At the next iteration, we pop St Albans from the front of the queue. We check St Alban’s neighbors.
These are Burlington (already visited) and Swanton.
So we append Swanton to the visited list and to the queue. At this point, the queue looks like this: ``` ['Middlebury', 'Swanton'] ``` At the next iteration, we pop Middlebury from the queue, and we check its neighbors.
Its neighbors are Burlington (already visited) and Rutland. Rutland is new, so we append it to the visited list and to the queue.
At this point, the queue looks like this: ``` ['Swanton', 'Rutland'] ``` At the next iteration, we pop Swanton from the front of the queue. Swanton’s only neighbor is St Albans and that’s already visited so we do nothing.
At this point, the queue looks like this: ``` ['Rutland'] ``` At the next iteration we pop Rutland from the front of the queue. Rutland’s neighbors are Bennington and Middlebury.
We’ve already visited Middlebury, but we haven’t visited Bennington, so we add it to the list of visited towns and to the queue.
At this point, the queue looks like this: ``` ['Bennington'] ``` At the next iteration we pop Bennington. Bennington’s sole neighbor is Rutland (already visited), so we do nothing.
At this point, the queue looks like this: ``` [] ``` With nothing added to an empty queue, the queue remains empty, and the while loop terminates.
(Remember: an empty list is falsey.) At this point we have a complete list of all the visited towns in the order they were visited: St Johnsbury, Montpelier, Newport, White River Junction, Burlington, Brattleboro, St Albans, Middlebury, Swanton, Rutland, and Bennington. ###### Why don’t we just iterate over the entire...
However, this is not always the case.
One reason we don’t just iterate over all keys in ----- a dictionary representing routes is that if we did so, we’d discover all towns on the map, rather than only those that can be reached from a given starting point. Consider highways connecting towns and cities in the Hawai’ian islands.
You can’t drive from Hilo to Honolulu—they’re on different islands. Sometimes we have graphs in which some vertices are not reachable from all other vertices.
This can occur in directed graphs (graphs in which the edges have directions, like one-way streets), or in disconnected graphs (graphs that contain vertices or components that aren’t connected to other components). ###### Applications Search algorithms on graphs have abundant applications, including solving mazes and...
On a sheet of paper, perform a breadth-first search, starting with Ethan. Write down the order in which the vertices are visited, and revise the queue as it changes.
Draw the graph if you think it will help you. Are all people (nodes) visited by breadth-first search? If not, why not? b. Is there a symmetry with respect to friendships?
How can we see this in the adjacency lists? ----- ###### Exercise 02 Consider this graph (a portion of Western Europe; edges indicate that one country can be reached from another by driving, without taking a ferry or airplane; dotted lines aren’t edges—they’re only there to associate labels with certain vertices): ...
Write the adjacency list representation of this graph using a dictionary. b. Is this graph cyclic or acyclic? Why? c.
Does it matter that countries as shown in the graph aren’t in their exact relative positions as they would be in a map of Europe? Why or why not? d.
Is this graph connected or disconnected? ###### Exercise 03 (challenge!) In the case of undirected graphs (the only kind shown in this text) edges do not have a direction, and thus if A is connected to B then B is connected to A.
We see this in the adjacency list representation: if Selim is a friend of Emma, then Emma is a friend of Selim. Write a function which takes the adjacency list representation of any arbitrary graph and returns True if this symmetry is correctly represented in the adjacency list representation and False otherwise.
Such a function could be used to validate an encoding of an undirected graph. ----- #### Appendix A ### Glossary ###### absolute value The absolute value of a number is its distance from the origin (0), that is, the magnitude of the number regardless of its sign.
In mathematics this is written with vertical bars on either side of the number or variable in question.
Thus |4| = 4 | −4| = 4 and generally, 𝑥≥0 |𝑥| = {[𝑥] −𝑥 𝑥< 0. The absolute value of any numeric literal, variable, or expression can be calculated with the Python built-in, abs(). ###### accumulator An accumulator is a variable that’s used to hold a cumulative result within a loop.
For example, we can calculate the sum of all numbers from 1 to 10, thus ``` s = 0 # s is the accumulator for n in range(1, 11): s += n # s is incremented at each iteration ###### adjacent ``` We say two vertices A, B, in a graph are adjacent if an edge exists in the graph with endpoints A and B. ###### alter...