Chapter 9 and 6 Flashcards

(70 cards)

1
Q

Are dictionaries mutable or immutable?

A

Mutable
- you can easily add, update and remove elements

Curly brackets {}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Differences between Dictionaries and Lists/Tuples

A
  • each element in a dictionary is a KEY-VALUE pair

{key: value, key: value}

  • dictionaries have NO ORDER (they are NOT A SEQUENCE of items)
  • therefore, dictionaries have NO INDEXES (instead, retrieve values using KEYS)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Create a new dictionary with has the following keys and values:
Chris 123
Katie 345
Joanne 567

A

dictNames = dict() #creates an empty dictionary

dictNames = {‘Chris’: 123, ‘Katie’: 345, ‘Joanne’: 567}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Is this appropriate?

myDict = { [1,2,3]: ‘Hi’, ‘Test’: 123 }

A

NO

Keys must be IMMUTABLE (strings, integers, floats, tuples)

Values can be ANYTHING (including lists)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you retrieve a value from a dictionary?

What happens when the key doesn’t exist?

A
  • NOT by indexes (don’t exist because there’s no order)
  • use KEYS instead

myDict[key] = value

  • if the key doesn’t exist, it’s like the same as when an index doesn’t exit => KeyError

*Therefore, it’s helpful to use:
.get(key, default)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to test if a key is already in the dictionary?

A
  • use IN and NOT IN operators

if key in myDict.keys():

or

if key in myDict:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Let’s say you have the following dictionary:

myDict = {‘John’: 85, ‘James’: 65, ‘Jacob’: 95}

What does myDict contain if the following is run:

myDict[‘John’] += 5

A

myDict = {‘John’: 90, ‘James’: 65, ‘Jacob’: 95}

John’s value is UPDATED

There are NO DUPLICATE KEYS in a dictionary

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Deleting key-value pair from a dictionary

what happens if that pair doesn’t exist?

A

del myDict[key]

If the key doesn’t exist => KeyError exception will be raised

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Is this allowed?

myDict = {‘abc’: 1, 999: ‘yada yada’, (3,6,9): [3,6,9]}

A

Yes

Mixed data types are allowed.

As long as KEYS are IMMUTABLE

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you iterate over all the keys in a dictionary?

A

for key in myDict.keys()

or

for key in myDict

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you clear the contents of a dictionary?

A

myDict.clear()

  • results in an empty dictionary {}

Alternatively, just set the variable myDict = {}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you get the value associated with a specified key?

A

myDict[key]
- will raise a KeyError exception if not found –> need IN operator first

or

myDict.get(key, default)

  • won’t raise a KeyError exception if not found
  • just returns a default value
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you return all the keys in a dictionary and their values as a sequence of tuples?

A

myDict.items()

Returns:
dict_items( [ (key, value), (key, value) ] )

*NOT actually a list; merely a dictionary representation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you return all the keys in a dictionary as a sequence of tuples?

A

myDict.keys()

Returns:
dict_keys( [ key, key, key ] )

  • you can ITERATE over these as a normal list (even though it’s NOT a list type)

To convert into a list:
list(myDict.keys())

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you return the value associated with a key and also remove that key-value pair from the dictionary?

What if that key doesn’t exist?

A

myDict.pop(key, default)

  • returns the value associated with key, then removes the key-value pair
  • if the key doesn’t exist, return the default (‘Entry not found’)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you return a randomly selected key-value pair as a tuple from a dictionary and remove that same key-value pair from the dictionary?

Example application: drawing a card from a standard deck

How can you store the key and value as separate variables?

What if the dictionary is empty?

A

myDict.popitem()

** NOT popitemS()

Returns: (Key, Value) –> TUPLE

You can use a multiple assignment statement to assign the returned key and value to individual variables:

e.g. k, v = myDict.popitem()

If empty dictionary:
- you can’t pop anything –> KeyError

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you return all the values in a dictionary as a sequence of tuples?

A

myDict.values()

Returns: dict_values( [value, value, value] )

  • NOT actually a list - it is considered a “view object”

To convert into a list:
list(myDict.values())

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Suppose you have the following dictionary:

myDict = {1: 4, ‘Hello’: [1,2]}

What are possible outputs from list(myDict.keys())?

A: [1, ‘Hello’]
B: [‘Hello’, 1]
C: [4, [1,2]]
D: [[1,2], 4]

A

A and B

  • the order of the resulting list is NOT guaranteed from a dictionary!!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Do you need a return statement in functions that takes a dictionary as a parameter and may modify it?

A

NO

- since dictionaries are MUTABLE like lists, you don’t need a return statement

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Given three dictionaries, associated with the variables,canadian_capitals,mexican_capitals, andus_capitals, that map provinces or states to their respective capitals, create a new dictionary that combines these three dictionaries, and associate it with a variable,nafta_capitals.

A

CANNOT do concatenation with dictionaries

Option 1: Loop through each of the 3 dictionaries to get the key and value, then add key and value to the new dictionary

nafta_capitals = {}
for key in us_capitals:
……nafta_capitals[key] = us_capitals[key]

Option 2: nafta_capitals.update(dictionary)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How do you get the max key in a dictionary?

A

max(myDict) works

BUT BETTER:

  1. Get list version of keys
    list( myDict.keys() )
  2. Get first key (stored in index 1), store as maxKey
    maxKey = list( myDict.keys() )[0]
  3. Iterate through each key and compare to maxKey. Update maxKey accordingly.

for key in myDict.keys():
….if key > maxKey:
……..maxKey = key

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are sets?

Are they mutable?

A

Sets store a collectionof elements inside curly brackets

  • sets are MUTABLE (like dictionaries and lists)
  • recall .add() and .update()
  • they are UNORDERED (like dictionaries)
  • they contain UNIQUE elements (like dictionary keys)
  • elements can be of different data types
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How do you create a set with the following elements?

{2,4,’Hello’}

A

set( [2, 4, ‘Hello’] )

  • argument in set() can only be ONE ARGUMENT (no commas or spaces!)
  • therefore, to initialize a set with multiple elements, pass objects that contain iterable objects (like a list)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Is this allowed?

set(‘Chris’, ‘Katie’, ‘John’)

A

NO

  • set() takes ONE argument (no commas or spaces)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Is this allowed? set('abcdef')
Yes - still one argument One possible set (due to unordered nature) {'a', 'c', 'b', 'e', 'd', 'f'} - each character is an element
26
Is this allowed? set('One Two Three')
YES - still considered one argument One possible set: {'t', 'o', 'r', 'e', 'h', 'n', 'w', ' '} - each character is an element - space takes up on element
27
How do you add an individual element to a set? Are exceptions raised when trying to add a duplicate element to a set?
mySet.add(element) - might not be added to the end of the set due to unordered properties! - if you try to add a duplicate item, NOTHING WILL HAPPEN (no exception errors raised)
28
How do you add groups of elements to a set? e.g. set1 = {1,2,3} Add: list1--> [4,5,6] set2--> {8,9,10} string1 --> 'abc'
mySet.update(list/tuple/string/another set) - elements in the group are added set1. update(list1) ==> possibly {1, 2, 3, 4, 5, 6} set1. update(set2) ==> possibly {1, 2, 3, 8, 9, 10} set1. update(string1) ==> possibly {1, 2, 3, 'a', 'b', 'c'}
29
How do you remove elements from a set?
Option 1: mySet.remove(item) - if the item does not exist, will raise a KeyError Option 2: mySet.discard(item) - if the item does not exist, will NOT raise a KeyError
30
Assume you have two sets: set1 and set2. How do you find all the elements in either set1 or set2 (in BOTH sets)?
.union(set) or | "elements in set1 OR set2" set1.union(set2) or set1 | set2 Returns a SET (duplicate elements only show up once)
31
Assume you have two sets: set1 and set2. How do you find all the elements shared by set1 and set2?
.intersection(set) or & "elements in set1 AND set2" set1.intersection(set2) or set1 & set2 Returns a SET
32
Assume you have two sets: set1 and set2. How do you find the elements in set2 but not in set1?
.difference(set) or - set2. difference(set1) - -> first set minus second set or set2 - set1
33
Assume you have two sets: set1 and set2. How do you find the elements that don't belong in either set?
.symmetric_difference(set) or ^ - visualize venn diagram --> shaded region are elements belonging only to one set set1. symmetric_difference(set2) or set1 ^ set2
34
How do you check if set1 is the subset of set2?
set1 <= set2 (less than or equal to) or set1.issubset(set2)
35
How do you check if set2 is the superset of set1?
set2 >= set1 (greater than or equal to) or set2.issuperset(set1)
36
After the following statement executes, what elements might be stored in the myset set? myset = set('www xxx yyy zzz')
- remember NO duplicates - all characters of a string become individual elements Possible set: {'w', 'x', 'y', 'z', ' '}
37
Given the string line, create a set of all the vowels in line. Associate the set with the variable vowels.
vowels = set() for ch in line: .....if ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch = 'u': ..........vowels.add(ch)
38
Assume you have the following dictionary (dictionary within a dictionary) students = {1010: {'name': 'Joe', 'Program': 'BAH', 'GPA': 3.5, 'Credits': 80}, 1020: {'name': 'Jane', 'Program': 'BCMP', 'GPA': '4.2', 'Credits': 102}} How do we access student 1010's program?
students[1010]['Program'] *double key calls!
39
Consider the following dictionary: d = {(1, 2): [5, 7, {3: "a"}, "cat"]} What is the length of this dictionary?
Length = # of key-value pair | = 1
40
Consider the following dictionary: d = {(1, 2): [5, 7, {3: "a"}, "cat"]} What is the value returned by d[(1, 2)]?
[5, 7, {3: "a"}, "cat"]
41
Consider the following dictionary: d = {(1, 2): [5, 7, {3: "a"}, "cat"]} How do you access 'a' in the sub dictionary?
d[(1,2)][2][3] - -> inside the list, you need INDEX 2 - -> inside the subdictionary, you need KEY 3
42
Consider the following dictionary: d = {(1, 2): [5, 7, {3: "a"}, "cat"]} How do you access 'a' in "cat"?
d[(1,2)][3][1]
43
Describe how writing and reading data from files work
WRITING file --> COPY data from RAM to the file READING file --> COPY data from file to the RAM
44
3 Steps when a Reading and Writing Files
1. Open the file (for reading, writing or appending) - creates a CONNECTION between the file and the program, and an ASSOCIATION between the file and the file object (e.g. variables like infile, outfile) 2. Process the file (write data or read data) 3. Close the file (disconnect the file from the program)
45
Types of Files x2
1. Binary File - not meant to be converted to text; data is stored and intended only for the program (cannot open the file with a text editor) 2. Text File - data is stored as text using a scheme like ASCII or unicode (series of characters) => STRING
46
File Access Methods x2
1. Sequential Access --> access data from start of the file to end of the file * * CISC 101 Example: Casette 2. Direct Access --> can directly jump to any piece of data without reading the data that comes before it Example: MP3 player
47
How do you open a file for reading, writing, and appending? What is the difference?
fileObject = open('Filename.txt', 'r') fileObject = open('Filename.txt', 'w') fileObject = open('Filename.txt', 'a') Reading Mode --> can only read content or lines (will get an error if you try to write/change content) Writing Mode --> allows you to write content to the file. If the file does not exist, a new file is created. If it does exist, the file's existing content is ERASED Append Mode --> allows you to write content to the end of a file. If it does not exist, a new file is created. *if file path is not specified in the file name, then the file must be saved in the SAME LOCATION as the program
48
How do you specify a file path when opening a file?
open(r'C:\Users\Blake\temp\test.txt') - add prefix r before the string - r stands for raw string
49
How do you write content to a file?
After opening the file for writing: fileName.write(STRING) - argument must be strings (so convert integers and floats) - if you want separate lines, + '\n' Don't forget to CLOSE the file: fileName.close()
50
How do read content from a file?
After opening the file for reading: Option 1: Read ENTIRE content as a string content = fileName.read() Option 2: Read a line as a string line = fileName.readline() - lines are identified as a string of characters ending with \n - each time you call .readline(), the READ POSITION advances to the NEXT line of the file
51
What does .readline() return is the file is empty?
An empty STRING
52
What does the following save in the file? outfile = open('test.txt', 'w') outfile. write('Hello!') outfile. write('My name is Jen.') outfile. write('What's your name?\n') outfile. write('Hey!') outfile.close()
Hello!My name is Jen.What's your name? | Hey!
53
What does the following display? Assume the file contains: John Locke David Hume Edmund Burke infile = open('Test.txt', 'r') fileContent = infile.read() print(fileContent) fileList = [] fileList.append(fileContent) print(fileList)
John Locke David Hume Edmund Burke #(print a string!!) ['John Locke\n\nDavid Hume\nEdmund Burke\n']
54
Suppose a file ('test.txt') contains: 25 100 60 Write code to find the total of the numbers
``` #Open the file for reading. infile = open('test.txt', 'r') ``` ``` #Read each line. line1 = infile.readline() --> '25\n' line2 = infile.readline() --> '100\n' line3 = infile.readline() --> '60\n' ``` #Convert strings into integers. ``` num1= int(line1) num2 = int(line2) num3 = int(line3) ``` #Find total. total = num1 + num2 + num3
55
How do you use loops to read data in a file?
FOR LOOPS: - iterates for each line in the file (automatically does read, no need for additional readline()) - For loop automatically KNOWS when the file ENDS for line in infile: WHILE LOOPS: - relies on read position - will end when reach empty line '' (no \n!) line = infile.readline() while line != '': .......(code) .......line = infile.readline()
56
Suppose a file contains: 28 48 53 What does the following code display after running: infile = open('Test.txt', 'r') for line in infile: ....print(line)
#if you were to read the entire file's content into one string, it would be '28\n48\n53\n' ``` #Line 1: '28\n' #Line 2: '48\n' #Line 3: '53\n' ``` #Recall print() already inserts a newline. 28 48 53 ``` #To avoid new lines, you must use line.rstrip('\n') or print(line, end='') ```
57
Is this allowed? Assume count is a variable run_time = input('Video #' + str(count) + ': ')
YES this works (concactenation! not commas)
58
# Fill out the following commented line below. Assume each number should appear on a line by itself in the file. outfile = open('numbers.txt', 'w') for num in range(1, 11): ......#what goes here outfile.close()
outfile.write(str(num) + '\n') Recall: - reading content from a file returns a STRING (you must convert to numeric literals before you can perform mathematical operations) - writing content to a file must be STRINGs
59
What are records (in relation to files)?
Records contain the COMPLETE set of data about an item Each individual piece of data in the record is called a FIELD Ex: Consider the following file ``` Ingrid Virgo 4587 Engineering Julia Cich 4588 Research Greg Young 4589 Marketing ``` There are 3 records, each record containing a name, an ID number, and department
60
How do you create records in Python?
Nothing fancy, just WRITE the FIELDS for the records, one after another - might be helpful to use a for or while loop to keep track of each record's iteration e. g. empFile = open('employees.txt', 'w') for count in (1, employees + 1): ....name = input('Name: ') .....id_num = input('ID number: ') ....dept = input('Department: ') ....empFile.write(name + '\n') ....empFile.write(id_num + '\n') ....empFile.write(dept + '\n') ``` #Display a blank line after asking 3 fields .....print() ``` empFile.close()
61
How do you search for a record? e.g. enter a name to see all records matching that name?
Assumptions: - you first need to KNOW how many fields per record - assume name is the first field Approach: - sift through every line until you hit one that matches your search ``` #Create a bool variable to use as a flag found = False ``` infile = open('EmpFile.txt', 'r') search = input('Enter name: ') name = infile.readline() while name != '': ....#first get the rest of the info to consistently ensure name equals names! ``` ....info2 = infile.readline() ....info3 = int(infile.readline()) ``` ....#CAN'T immediately do name == search due to \n characters ....name = name.rstrip('\n') ....if name == search: ........ found = True ....name.readline()
62
How do you modify a record?
Approach: - First, create a new empty file to transfer all the line items to - Second, find a match to your input - Third, transfer all the old line items one at a time, modifying the field as needed (e.g. deleting it, updating it) - Fourth, delete the original file - Fifth, rename the second file to the original file's name
63
How do you delete a file given the name?
import os os.remove('filename.txt')
64
How do you rename file names, given the old and new file names?
import os os.rename('oldfileName.txt', 'newFileName.txt')
65
What are some common exceptions?
Exception are errors found when the program is running, which cause the program to STOP ``` ValueError (including trying to convert letters to integer) KeyError IndexError IOError ZeroDivisionError ```
66
How do you use try/except to handle exceptions?
try suite -> here is where you put your normal code that potentially could raise an exception - if an exception is raised, the program LEAVES the try suite and proceeds to the except clauses - if no exceptions are raised, then the except clause and handlers are SKIPPED except ExceptionName: - if the exception raised matches the ExceptionName, the statements under this statement will execute - afterwards, the program RESUMES execution of the statements FOLLOWING the try/except statements - if the exception raised does NOT match the ExceptionName and there's no catch-all except statement, then the error message will display
67
How do you display the exception's default error message?
except ExceptionName as err: ....print(err) - err is a variable (exception object) that contains the default error message If you have only one catch-all except clause: except Exception as error
68
try/except/ELSE clause What does the else clause do?
else: ....statements Else block will execute after try suite if the TRY SUITE has NO EXCEPTIONS raised - if an exception was raised, the else suite is SKIPPED
69
try/except/FINALLYclause What does the finally clause do?
REGARDLESS of whether an exception was raised or not, the finally clause will execute - appears after the try and except blocks PURPOSE: - perform cleanup operations like closing files
70
Three variables, x, y and z, supposedly hold strings of digits, suitable for converting to integers. Write code that converts these to integers and print the sum of these three integers. However, if any variable has a value that cannot be converted to an integer, print out, the string "bad value(s) in: " followed by the names of the variables that have bad values (separated by spaces, in alphabetically ascending order). For example, if the values of x, y and z were respectively "3", "9", "2" then the number 14 would be printed; but if the values were "abc", "15", "boo" then the output would be: bad value(s) in: x z
sum = 0 badValues = '' try: ...sum += int(x) except ValueError: ...badValues += ' x' try: ...sum += int(y) except ValueError: ...badValues += ' y' try: ...sum += int(z) except ValueError: ...badValues += ' z' if badValues == '': ...print(sum) else: ...print('bad value(s) in:' + badValues)