COMP SCI CH 9
You can delete an existing key-value pair from a dictionary with the
del statement
Does a set allow you to store duplicate elements?
no
1 >>> myset = set([1, 2, 3]) [Enter] 2 >>> myset.update('abc') [Enter] 3 >>> myset [Enter]
{'a', 1, 2, 3, 'c', 'b'}
After the following statement executes, what elements will be stored in the myset set? myset = set('www xxx yyy zzz')
{'w', ' ', 'y', 'z', 'x'}
After the following statement executes, what elements will be stored in the myset set? myset = set(['www', 'xxx', 'yyy', 'zzz'])
{'www', 'xxx', 'yyy', 'zzz'}
1 >>> myset = set([1, 2, 3]) [Enter] 2 >>> myset.update([4, 5, 6]) [Enter] 3 >>> myset [Enter]
{1, 2, 3, 4, 5, 6}
After the following statement executes, what elements will be stored in the myset set? myset = set([1, 2, 2, 3, 4, 4, 4])
{1, 2, 3, 4}
1 >>> myset = set([1, 2, 3, 4, 5]) [Enter] 2 >>> myset [Enter] 3 {1, 2, 3, 4, 5} 4 >>> myset.clear() [Enter] 5 >>> myset [Enter]
set()
|
union of two sets
k, v = dictionary.popitem()
k and v are variables. After the statement executes, k is assigned a randomly selected key from the dictionary, and v is assigned the value associated with that key. The key-value pair is removed from the dictionary.
Each element that is stored in a dictionary has two parts:
key and value
phonebook = {'Chris':'555−1111', [Enter] 'Katie':'555−2222', [Enter] 'Joanne':'555−3333'} [Enter] for key, value in phonebook.items(): [Enter] print(key, value) [Enter] [Enter] Chris 555−1111 Joanne 555−3333 Katie 555−2222
using for loop to iterate over tuples in a sequence using items
Returns all the values in the dictionary as a sequence of tuples.
values for val in phone.values(): print(val) 123 456 789
# This is an ERROR! myset = set('one', 'two', 'three') # This does not do what we intend. myset = set('one two three') # OK, this works. myset = set(['one', 'two', 'three'])
you can pass no more than one argument to the set function To create the set that we want, we have to pass a list containing the strings 'one', 'two', and 'three' as an argument to the set function
After the following statement executes, what elements will be stored in the myset set? myset = set('Jupiter')
{'J', 'u', 'p', 'i', 't', 'e'}
After the following code executes, what elements will be members of set3? set1 = set(['a', 'b', 'c']) set2 = set(['b', 'c', 'd']) set3 = set1.symmetric_difference(set2)
{'a', 'd'}
1 >>> set1 = set([1, 2, 3, 4]) [Enter] 2 >>> set2 = set([3, 4, 5, 6]) [Enter] 3 >>> set3 = set1 | set2 [Enter] 4 >>> set3 [Enter]
{1, 2, 3, 4, 5, 6}
1 >>> set1 = set([1, 2, 3, 4]) [Enter] 2 >>> set2 = set([3, 4, 5, 6]) [Enter] 3 >>> set3 = set1.union(set2) [Enter] 4 >>> set3 [Enter]
{1, 2, 3, 4, 5, 6}
After the following statement executes, what elements will be stored in the myset set? myset = set([10, 9, 8]) myset.update([1, 2, 3])
{1, 2, 3, 8, 9, 10}
myset. = set() myset.add(1) myset.add(2) myset.add(3) print(myset)
{1, 2, 3}
1 >>> set1 = set([1, 2, 3, 4]) [Enter] 2 >>> set2 = set([3, 4, 5, 6]) [Enter] 3 >>> set3 = set1 ˆ set2 [Enter] 4 >>> set3 [Enter]
{1, 2, 5, 6}
1 >>> set1 = set([1, 2, 3, 4]) [Enter] 2 >>> set2 = set([3, 4, 5, 6]) [Enter] 3 >>> set3 = set1.difference(set2) [Enter] 4 >>> set3 [Enter] 1 >>> set1 = set([1, 2, 3, 4]) [Enter] 2 >>> set2 = set([3, 4, 5, 6]) [Enter] 3 >>> set3 = set1 − set2 [Enter] 4 >>> set3 [Enter]
{1, 2}
After the following code executes, what elements will be members of set3? set1 = set([1, 2, 3, 4]) set2 = set([3, 4, 5, 6]) set3 = set1.difference(set2)
{1, 2}
After the following code executes, what elements will be members of set3? set1 = set([10, 20, 30]) set2 = set([100, 200, 300]) set3 = set1.union(set2)
{10, 20, 30, 100, 200, 300}
After the following code executes, what elements will be members of set3? set1 = set([1, 2, 3, 4]) set2 = set([3, 4, 5, 6]) set3 = set1.intersection(set2)
{3, 4}
1 >>> set1 = set([1, 2, 3, 4]) [Enter] 2 >>> set2 = set([3, 4, 5, 6]) [Enter] 3 >>> set3 = set1.intersection(set2) [Enter] 4 >>> set3 [Enter] 1 >>> set1 = set([1, 2, 3, 4]) [Enter] 2 >>> set2 = set([3, 4, 5, 6]) [Enter] 3 >>> set3 = set1 & set2 [Enter] 4 >>> set3 [Enter]
{3,4}
After the following code executes, what elements will be members of set3? set1 = set([1, 2, 3, 4]) set2 = set([3, 4, 5, 6]) set3 = set2.difference(set1)
{5, 6}
After the following statement executes, what elements will be stored in the myset set? myset = set([10, 9, 8]) myset.update('abc')
{8, 9, 10, 'a', 'b', 'c'}
phone = {"Bob" : "1" "Sue" : "2" "Tom : "3"} for key in phone: print(key) for key in phone: print(key, phone[key])
Bob Sue Tom Bob 1 Sue 2 Tom 3
You can use the in operator to determine whether a value exists in a set.
1 >>> myset = set([1, 2, 3]) [Enter] 2 >>> if 1 in myset: [Enter] 3 print('The value 1 is in the set.') [Enter] [Enter] 4 5 The value 1 is in the set.
num_items = len(phone) print(num_items)
3
1 >>> myset = set(['a', 'b', 'c']) [Enter] 2 >>> for val in myset: [Enter] 3 print(val) [Enter] [Enter]
4 5 a 6 c 7 b 8 >>>
phone = {"BOB": "555", "SUE": "666", "JOE": "777"} phone["TOM"] = "888" phone["MOE"] = "999"
Adding elements to existing dictionary
an object that stores a collection of data. Each element in a dictionary has two parts: a key and a value. You use a key to locate a specific value.
DICTIONARY
phone = {"BOB": "555", "SUE": "666", "JOE": "777"} phone["KATYLN"] what happens?
KEYERROR KEY IS NOT IN DICTIONARY
if a key does not exist when retrieving a value, what happens?
KeyError exception
You can remove an item from a set with either the remove method or the discard method. You pass the item that you want to remove as an argument to either method, and that item is removed from the set. The only difference between the two methods is how they behave when the specified item is not found in the set.
The remove method raises a KeyError exception, but the discard method does not raise an exception.
populations = {'New York': 8398748, 'Los Angeles': 3990456, 'Chicago': 2705994,'Houston': 2325502, 'Phoenix': 1660272, 'Philadelphia': 1584138} largest = {} for k, v in populations.items(): if v > 2000000: largest[k] = v {'New York': 8398748, 'Los Angeles': 3990456, 'Chicago': 2705994, 'Houston': 2325502}
This type of operation can also be accomplished by adding an if clause to a dictionary comprehension. Here is the general format: {result_expression iteration_expression if_clause} The if clause acts as a filter, allowing you to select certain items from the input sequence. The following code shows how we can rewrite the previous code using a dictionary comprehension with an if clause: largest = {k:v for k,v in populations.items() if v > 2000000} In the dictionary comprehension, the iteration expression is: for k,v in populations.items() The if clause is: if v > 2000000 And the result expression is: k:v
After the following statement executes, what elements will be stored in the myset set? myset = set(25)
TypeError because you are trying to create a set from an integer, and it's not a valid input for creating a set directly. myset = set([25]) # Create a set with a single element, 25
scores = {"BOB": [1,2,3], "SUE": [4,5,6], "JOE: [7,8,9]} bobscore = scores["BOB"] print(bobscore)
[1,2,3]
dictionary_name[key] = value dictionary_name is the variable that references the dictionary, key is a key. If key already exists in the dictionary, its associated value will be changed to value. If the key does not exist, it will be added to the dictionary, along with value as its associated value.
adding elements to an existing dictionary
to create an empty dictionary and then add elements to it as the program executes. You can use ___
an empty set of curly braces phone = {} built in dict() method
keys in dictionary must be immutable objects but their associated values can be
any type of object. values can be lists scores = {"BOB": [1,2,3], "SUE": [4,5,6], "JOE: [7,8,9]} bobscore = scores["BOB"] print(bobscore) [1,2,3]
phonebook = dict()
built in dict() method
string comparisons are
case sensitive ["bOB"] will not locate the key "BOB"
Clears the contents of a dictionary.
clear dictionary.clear() phone.clear()
You can create a dictionary by enclosing the elements inside a set of curly braces ( {} ). An element consists of a key, followed by a colon, followed by a value. The elements are separated by commas.
creating a dictionary phone = {"BOB": 123, "SUE": 456, "TOM": "789}"
del dictionary_name[key] del phone["BOB"]
delete an existing key value pair if key does not exist KeyError raised
dictionaries are not
dictionaries arent sequences lists, tuples, strings are sequences
expression that reads a sequence of input elements and uses those input elements to produce a dictionary.
dictionary comprehension
>>> numbers = [1, 2, 3, 4] [Enter] >>> squares = {item:item**2 for item in numbers} [Enter] >>> numbers [Enter] [1, 2, 3, 4] >>> squares [Enter] {1: 1, 2: 4, 3: 9, 4: 16}
dictionary comprehension right side of = result expression item:item**2 iteration expression for item in numbers
method to get the difference of two sets. the elements that appear in set1 but do not appear in set2.
difference set1.difference(set2) set1 - set2
You CANNOT have ____ in a dictionary. When you assign a value to an existing key, the new value replaces the existing value.
duplicate keys
How do you create an empty set?
empty_set = set() empty_set.add(42) print(empty_set) # Output: {42}
to iterate over all the keys in a dictionary you can use the ___
for loop for var in dict: statement statement etc. var is the name of a variable and dictionary is the name of a dictionary. This loop iterates once for each element in the dictionary. Each time the loop iterates, var is assigned a key.
You can use the for loop in the following general format to iterate over all the elements in a set:
for var in set: statement statement etc.
Gets the value associated with a specified key. If the key is not found, the method does not raise an exception. Instead, it returns a default value.
get dictionary.get(key,default) val = phone.get("BOB", "entry not found") print(val) >>>555 val2 = phone.get("cat",entrynotfound") print(val2) >>>entrynotfound dictionary is the name of a dictionary, key is a key to search for in the dictionary, default is a default value to return if the key is not found. When the method is called, it returns the value that is associated with the specified key. If the specified key is not found in the dictionary, the method returns default.
KeyError exception is raised if you try to retrieve a value from a dictionary using a nonexistent key. To prevent such an exception, you can use the _____ operator to determine whether a key exists before you try to use it to retrieve a value.
in operator phone = {"BOB": "555", "SUE": "666", "JOE": "777"} if "BOB" in phone: print(phone["BOB"]) 555
How can you determine whether a specific element exists in a set?
in operator or the set methods like contains() or issubset() depending on your specific needs. Here are a few methods you can use:
&
intersection
a set that contains only the elements that are found in both sets. I
intersection set1.intersection(set2) set1 & set2
Returns all the keys in a dictionary and their associated values as a sequence of tuples. They are returned as a special type of sequence known as a dictionary view. Each element in the dictionary view is a tuple, and each tuple contains a key and its associated value.
items phone.items() [("BOB", "123"), ("SUE","456"), ("JOE","789")] returned as dictionary view where each element is a tuple, containing key and value pairs.
removes the key-value pair that was last added to the dictionary. returns key value pair as a tuble
popitem dictionary.popitem() k, v = dictionary.popitem()
phonebook = {'Chris':'555−1111', [Enter] 2 'Katie':'555−2222', [Enter] 3 'Joanne':'555−3333'} [Enter] 4 >>> phonebook [Enter] 5 {'Chris': '555−1111', 'Joanne': '555−3333', 'Katie': '555−2222'} 6 >>> key, value = phonebook.popitem() [Enter] 7 >>> print(key, value) [Enter] 8 Chris 555−1111 9 >>> phonebook [Enter] 10 {'Joanne': '555−3333', 'Katie': '555−2222'} 11 >>>
key, value = dictionary.popitem()
You can add new ____ to a dictionary with an assignment statement
key- value pairs
Which part of a dictionary element must be immutable?
keys
Returns all the keys in a dictionary as a sequence of tuples. Returns as dictionary view which is a type of sequence
keys phone.keys() ["BOB","SUE","JOE"] for key in phone.keys(): print(key) BOB SUE JOE
to get the number of elements in a dictionary use the ___
len function
As with lists, tuples, and dictionaries, you can use the ____ to get the number of elements in a set.
len function myset = ([1,2,3]) len(myset) 3
multiple variables are being assigned at once. In the general format, k and v are variables. After the statement executes, k is assigned a randomly selected key from the dictionary, and v is assigned the value associated with that key. The key-value pair is removed from the dictionary.
multiple assignment
Dictionaries are ____
mutable objects
sets are ____
mutable objects, you can add and remove items from them.
How do you determine the number of elements in a set?
myset = set([1, 2, 3, 4, 5]) count = len(myset) print("Number of elements in the set:", count)
determines whether a key doesnt exist
not in if "RAY" not in phone: print("Ray not found") Ray not found
Elements from a dictionary are
not stored in any particular order
keys
objects of any type, MUST BE immutable CANNOT BE LISTS OR ANY TYPE OF IMMUTABLE OBJECT
dictionary comprehension is on the __ side of the = operator is enclosed with ___ begins with ___ followed by an ____
on the right side of the = operator enclosed in curly braces begins with a result expression item: item**2 followed by an iteration expression for item in numbers squares = {item:item**2 for item in numbers}
phone = {"BOB": "555", "SUE": "666", "JOE": "777"} how do i retrieve the numbers from the keys?
phone["BOB"] phone["SUE"] phone["JOE"]
Returns the value associated with a specified key and removes that key-value pair from the dictionary. If the key is not found, the method returns a default value.
pop dict.pop(key,default) num = phone.pop("BOB", "entry not found") print(num) "555"
dictionary_name[key] dictionary_name is the variable that references the dictionary, and key is a key. If the key exists in the dictionary, the expression returns the value that is associated with the key. If the key does not exist, a KeyError exception is raised.
retrieve a value from a dictionary
All the elements in a set must be unique. No two elements can have the same value. unordered, which means that the elements in a set are not stored in any particular order. The elements that are stored can be of different data types.
set
an object that stores a collection of data in the same way as mathematical sets.
set myset = set() myset = set("Abc") myset = set(["a","b","c"])
an expression that reads a sequence of input elements and uses those input elements to produce a set.
set comprehension set1 = set([1, 2, 3, 4, 5]) set2 = {item for item in set1}
1 >>> set1 = set([1, 2, 3, 4]) [Enter] 2 >>> set2 = set([2, 3]) [Enter] 3 >>> set2 <= set1 [Enter] 4 True 5 >>> set1 >= set2 [Enter] 6 True 7 >>> set1 <= set2 [Enter] 8 False
subset superset
1 >>> set1 = set([1, 2, 3, 4]) [Enter] 2 >>> set2 = set([2, 3]) [Enter] 3 >>> set2.issubset(set1) [Enter] 4 True 5 >>> set1.issuperset(set2) [Enter] 6 True
subset superset
^
symmetric difference
a set that contains the elements that are not shared by the sets. In other words, it is the elements that are in one set but not in both.
symmetric difference set1.symmetric_difference(set2) set1 ^ set 2
What is the difference between the remove and discard methods?
the key difference is in how they handle the case where the element to be removed is not in the set. remove() raises an error, while discard() does not.
is a set that contains all the elements of both sets.
union set1.union(set2) set1 | set2
Are the elements of a set ordered or unordered?
unordered